3143 二叉树的序遍历
2017-05-20 16:24
162 查看
题目描述 Description
求一棵二叉树的前序遍历,中序遍历和后序遍历
输入描述 Input Description
第一行一个整数n,表示这棵树的节点个数。
接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。
输出描述 Output Description
输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。
样例输入 Sample Input
5
2 3
4 5
0 0
0 0
0 0
样例输出 Sample Output
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
#include<iostream>
using namespace std;
int n,x,y;
struct node
{
int left;
int right;
}tree[256];
void preorder(int a)
{
cout<<a<<" ";
if(tree[a].left) preorder(tree[a].left);
if(tree[a].right) preorder(tree[a].right);
}
void inorder(int a)
{
if(tree[a].left) inorder(tree[a].left);
cout<<a<<" ";
if(tree[a].right) inorder(tree[a].right);
}
void postorder(int a)
{
if(tree[a].left) postorder(tree[a].left);
if(tree[a].right) postorder(tree[a].right);
cout<<a<<" ";
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
tree[i].left=x;
tree[i].right=y;
}
preorder(1);
cout<<endl;
inorder(1);
cout<<endl;
postorder(1);
}
求一棵二叉树的前序遍历,中序遍历和后序遍历
输入描述 Input Description
第一行一个整数n,表示这棵树的节点个数。
接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。
输出描述 Output Description
输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。
样例输入 Sample Input
5
2 3
4 5
0 0
0 0
0 0
样例输出 Sample Output
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
#include<iostream>
using namespace std;
int n,x,y;
struct node
{
int left;
int right;
}tree[256];
void preorder(int a)
{
cout<<a<<" ";
if(tree[a].left) preorder(tree[a].left);
if(tree[a].right) preorder(tree[a].right);
}
void inorder(int a)
{
if(tree[a].left) inorder(tree[a].left);
cout<<a<<" ";
if(tree[a].right) inorder(tree[a].right);
}
void postorder(int a)
{
if(tree[a].left) postorder(tree[a].left);
if(tree[a].right) postorder(tree[a].right);
cout<<a<<" ";
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
tree[i].left=x;
tree[i].right=y;
}
preorder(1);
cout<<endl;
inorder(1);
cout<<endl;
postorder(1);
}
相关文章推荐
- wiki 3143 二叉树的前序、中序及后序遍历
- [codevs3143] 二叉树的序遍历
- 3143 二叉树的序遍历
- code[vs] 3143 二叉树的序遍历
- 3143 二叉树的序遍历(维基oi)
- codevs 3143 二叉树的序遍历
- 3143 二叉树的序遍历codevs
- wiki 3143 二叉树的前序、中序及后序遍历
- 3143 二叉树的序遍历
- CODEVS 3143 二叉树的序遍历
- codevs 3143 二叉树的序遍历
- *题目记录 codevs3143 二叉树的序遍历
- wikioi 3143 二叉树的序遍历
- codevs 3143 二叉树的序遍历
- 3143 二叉树的序遍历——http://codevs.cn/problem/3143/
- CODE[VS]_3143二叉树的序遍历
- 3143 二叉树的序遍历
- codeVS 3143 二叉树的序遍历
- Codves 3143 二叉树的序遍历 递归
- 二叉树的遍历