通过使用栈可以以非递归方式实现二叉树的中序遍历。
例如,假设遍历一个如下图所示的 6 节点的二叉树(节点编号从 1 到 6)。
则堆栈操作为:push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop()。
我们可以从此操作序列中生成唯一的二叉树。
你的任务是给出这棵树的后序遍历。
输入格式
第一行包含整数 N,表示树中节点个数。
树中节点编号从 1 到 N。
接下来 2N 行,每行包含一个栈操作,格式为:
Push X,将编号为 X 的节点压入栈中。
Pop,弹出栈顶元素。
输出格式
输出这个二叉树的后序遍历序列。
数据保证有解,数和数之间用空格隔开,末尾不能有多余空格。
数据范围
1≤N≤30
输入样例:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
输出样例:
3 4 2 6 5 1
可以看作Push即有相应的孩子,Pop则相应孩子为空
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node*l,*r;
};
string s;
int n;
int num=0;
void create(struct node*&root)
{
int shu;
cin >>shu;
root = new node;
root->data=shu;
cin >>s;
if(s=="Push")
create(root->l);
else
root->l=NULL;
cin >> s;
if(s=="Push")
create(root->r);
else
root->r=NULL;
}
void houxv(struct node*root)
{
if(root)
{
houxv(root->l);
houxv(root->r);
num++;
cout <<root->data;
if(num!=n)
cout <<" ";
}
}
int main()
{
cin >> n;
cin >>s;
struct node*root=NULL;
create(root);
houxv(root);
return 0;
}