【MOOC】03-树3 Tree Traversals Again (25分)
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.
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
通过观察可以发现,该题实际上是给出二叉树的前序和中序遍历,然后输出该二叉树的后序遍历。测试样例一直过不去,后来发现是n-i-1,不是n-i+1,注意每次递归时下标的变化。
说明:bef代表before(前序起始),mid代表in(中序起始),aft代表after(后序起始)。pre为前序遍历,in为中序遍历,post为后序遍历
#include <iostream>
#include <stack>
using namespace std;
int pre[35],in[35],post[35];
void order(int bef,int mid,int aft,int n){
if(n<1)
return;
if(n==1)//递归终止条件
post[aft] = pre[bef];
else{
int tmp = pre[bef];
post[aft+n-1] = tmp;
int i;
for(i = 0;i<n;i++){
if(in[mid+i]==tmp)
break;
}
order(bef+1,mid,aft,i);
order(bef+i+1,mid+i+1,aft+i,n-i-1);
}
}
void print(int n){
if(n<1)
return;
cout << post[0];
for(int i = 1;i<n;i++)
cout << " " << post[i];
}
int main(){
int n,x,m;
cin >> n;
stack<int> s;
int k = 0,p = 0;
string op;
//注意是2*n,因为n个结点的中序遍历对应2*n次出栈和入栈
for(int i = 0;i<2*n;i++){
cin >> op;
if(op=="Push"){
cin >> x;
pre[k++] = x;
s.push(x);
}
else if(op=="Pop"&&!s.empty()){
m = s.top();
s.pop();
in[p++] = m;
}
}
order(0,0,0,n);
print(n);
return 0;
}
上一篇: JAVA中 toString()、String.valueOf()和强制转换
下一篇: 环境搭建