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
stack中的push顺序为二叉树先序遍历的结果,stack中的pop的顺序为二叉树中序遍历的结果,可以根据二叉树先序、中序遍历的结果来重建二叉树,进而进行后序遍历
满分代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N=35;
struct node{
int v;//数据域
node *left=NULL;
node *right=NULL;
};
int pre[N],in[N];//存储中序遍历的结果
int n;//结点的个数
//先序+中序建树的过程
node* create(int prel,int prer,int inl,int inr){
if(prel>prer){
return NULL;
}
node *root=new node;
root->v=pre[prel];
int k;
for(k=inl;k<=inr;k++){
if(in[k]==pre[prel])
break;
}
int numleft=k-inl;
root->left=create(prel+1,prel+numleft,inl,k-1);
root->right=create(prel+numleft+1,prer,k+1,inr);
return root;
}
int flag=0;
//后序遍历的过程
void postorder(node *root){
if(root==NULL) return;
postorder(root->left);
postorder(root->right);
if(flag) printf(" ");
printf("%d",root->v);
flag=1;
}
int main(){
scanf("%d",&n);
int pre_num=-1,in_num=-1;
string s;
int x;
stack<int>st;
for(int i=1;i<=2*n;i++){
cin>>s;
if(s=="Push"){//push的输入为树的先序,pop的输出为树的中序
cin>>x;
st.push(x);
pre_num++;
pre[pre_num]=x;
}else{
in_num++;
in[in_num]=st.top();
st.pop();
}
}
node *root=create(0,pre_num,0,in_num);
postorder(root);
return 0;
}
本文介绍如何使用栈的push和pop操作序列生成并遍历一棵二叉树,通过给定的节点push顺序(先序遍历)和pop顺序(中序遍历),可以唯一确定一棵二叉树,并实现其后序遍历。
1492

被折叠的 条评论
为什么被折叠?



