An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69#include<iostream>
#include<stack>
#include<vector>
using namespace std;
vector<int> Tree[30];
vector<int> ans;
void postOrderTraversal(int fNode) //fNode : father node
{
if(Tree[fNode].size() == 1)
{
postOrderTraversal(Tree[fNode][0]);
ans.push_back(fNode);
}
else if(Tree[fNode].size() == 2)
{
postOrderTraversal(Tree[fNode][0]);
postOrderTraversal(Tree[fNode][1]);
ans.push_back(fNode);
}
else
{
ans.push_back(fNode);
}
}
int main()
{
int N = 0;
cin >> N;
string str;
int val;
stack<int> stk;
int popVal = -1;
int root = 0;
for(int i = 0; i < N * 2; ++i)
{
cin >> str;
if(str == "Push")
{
cin >> val;
if(i != 0 && popVal == -1)
{
Tree[stk.top()].push_back(val);
}
else if(i == 0)
{
root = val;
}
if(popVal != -1)
{
Tree[popVal].push_back(val);
}
stk.push(val);
popVal = -1;
}
else if(str == "Pop")
{
popVal = stk.top();
stk.pop();
}
}
postOrderTraversal(root);
for(int i = 0; i < ans.size(); ++i)
{
cout << ans[i] << ((i == ans.size() - 1)?"\n":" ");
}
return 0;
}
这是我第二次一遍就能AC的代码!
思路:
push即为先序遍历序列
pop即为中序遍历序列
知道这两个序列,就可以唯一确定一棵树,然后在后序遍历即可。
如何分辨push进来的元素是哪个结点(父结点)的左子结点还是右子结点?
每次push之前,如果之前那次是pop操作,则父结点为pop的那个元素,如果之前依然是push操作,那么父结点就是栈顶元素。代码中设置一个popVal来判断上一次操作是pop还是push,是pop,记录pop元素的值,以便接下来push操作找父结点。