思路:
后续遍历dfs,除了常规的先左右后根处理
根处理:1.叶子节点 or 2.左右都有孩子的处理外
特别注意:无左孩子 + 有右孩子的处理
src:
#include<bits/stdc++.h>
using namespace std;
// 左右根
struct node {
string data;
int left = -1;
int right = -1;
}nodeList[25];
// postTraversal
string postTraversal(int root) {
string ans = "";
// 一个很特殊的情况(只有右孩子,那么就直接把符号放前面)
if(nodeList[root].right != -1 && nodeList[root].left == -1) {
ans = "(" + nodeList[root].data + postTraversal(nodeList[root].right) + ")";
return ans;
}
if(nodeList[root].left != -1) ans += postTraversal(nodeList[root].left);
if(nodeList[root].right != -1) ans += postTraversal(nodeList[root].right);
if(nodeList[root].left == -1 && nodeList[root].right == -1)
ans += "(" + nodeList[root].data + ")";
else if(nodeList[root].data == "+" || nodeList[root].data == "*" || nodeList[root].data == "-" ||
nodeList[root].data == "/" || nodeList[root].data == "%" || nodeList[root].data == "^" ||
nodeList[root].data == "&")
ans = "(" + ans + nodeList[root].data + ")";
return ans;
}
int main() {
int n;
cin >> n;
unordered_map<int, int> child;
for(int i = 1; i <= n; i++) {
string _data;
int _left, _right;
cin >> _data >> _left >> _right;
nodeList[i].data = _data;
nodeList[i].left = _left;
nodeList[i].right = _right;
if(_left != -1) child[_left] = 1;
if(_right != -1) child[_right] = 1;
}
// find root
int root = -1;
for(int i = 1; i <= n; i++) {
if(child[i] == 0) {
root = i;
break;
}
}
// cout << root << endl;
string ans = postTraversal(root);
cout << ans << endl;
}
总结:
分类讨论!