官网
1086. Tree Traversals Again (25)
时间限制
200 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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.
Sample 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.依据中序遍历的非递归形式用到的堆的状态,来构造树并输出后序遍历。
解题思路
- 1.用一个deque保持跟输入一致的状态,例如输入push,我们deque也跟着push这个数,这样,我们取deque的最后一个元素now,我们可以发现,如果下一步的动作是push,后面跟着的值为v,那么v不是他的左孩子就是他的右孩子,这一点可以根据now有没有左孩子来判断,如果下一步的动作是pop,那么代表now的左孩子或者右孩子为空,这个也可以根据他的左孩子是否被”访问”过有关系,也很好判断。构造完树后输出就很简单了。
AC代码
#include<iostream>
#include<vector>
#include<deque>
#include<map>
#include<string>
using namespace std;
map<int, int> left1;
map<int, int>right1;
//int left1[31], right1[31];
bool flag = true;
void postOrder(int root){
if (left1[root]!=0&&left1[root]!=-1)
{
postOrder(left1[root]);
}
if (right1[root] != 0 && right1[root] != -1)
{
postOrder(right1[root]);
}
if (flag)
{
cout << root;
flag = false;
}
else{
cout << " " << root;
}
}
int main()
{
int n,root;
cin >> n;
string a;
int v;
cin >> a >> v;
root = v;
//用deque来跟踪输入的动作
deque<int> dq;
dq.push_back(v);
int now = dq.back();
for (int i = 0; i < 2*n-1; i++)
{
//int now = dq.back();
cin >> a;
if (a[1]=='u')
{
cin >> v;
//判断输入的是now的左孩子还是now的右孩子
if (left1[now]==0)
{
left1[now] = v;
}
else{
right1[now] = v;
}
dq.push_back(v);
now = dq.back();
}
else
{
//判断now的哪一个孩子为空
if (left1[now]==0)
{
left1[now] = -1;
}
else
{
right1[now] = -1;
}
now = dq.back();
dq.pop_back();
}
}
//后序输出
postOrder(root);
cout << endl;
return 0;
}