二叉树的遍历
题目描述
有一个 n(n≤106) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 n),建立一棵二叉树(根节点的编号为 11),如果是叶子结点,则输入 0 0
。
建好树这棵二叉树之后,依次求出它的前序、中序、后序列遍历。
输入格式
第一行一个整数 n,表示结点数。
之后 n 行,第 i 行两个整数 l、r,分别表示结点 i 的左右子结点编号。若 l=0 则表示无左子结点,r=0 同理。
输出格式
输出三行,每行 n 个数字,用空格隔开。
第一行是这个二叉树的前序遍历。
第二行是这个二叉树的中序遍历。
第三行是这个二叉树的后序遍历。
样例 #1
样例输入 #1
7
2 7
4 0
0 0
0 3
0 0
0 5
6 0
样例输出 #1
1 2 4 3 7 6 5
4 3 2 1 6 5 7
3 4 2 5 6 7 1
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+5;
struct node
{
int data,left,right;
} tree[N];
void preorder(int id)
{
if(id==0)
{
return ;
}
cout<<id<<" ";
preorder(tree[id].left);
preorder(tree[id].right);
}
void inorder(int id)
{
if(id==0)
{
return ;
}
inorder(tree[id].left);
cout<<id<<" ";
inorder(tree[id].right);
}
void postorder(int id)
{
if(id==0)
{
return ;
}
postorder(tree[id].left);
postorder(tree[id].right);
cout<<id<<" ";
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>tree[i].left>>tree[i].right;
tree[i].data=i;
}
preorder(1);
cout<<endl;
inorder(1);
cout<<endl;
postorder(1);
return 0;
}