codevs3143 二叉树的序遍历

难度等级:白银

3143 二叉树的序遍历

题目描述 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

数据范围及提示 Data Size & Hint

n <= 16

三种序遍历见上文2010 求后序遍历有解释

#include<iostream>
using namespace std;
int n;
int l[20],r[20];
void preorder(int k)//先序
{
    cout<<k<<' ';
    if(l[k]) preorder(l[k]);
    if(r[k]) preorder(r[k]);
}
void inorder(int k)//中序
{
    if(l[k]) inorder(l[k]);
    cout<<k<<' ';
    if(r[k]) inorder(r[k]);
}
void postorder(int k)//后序
{
    if(l[k]) postorder(l[k]);
    if(r[k]) postorder(r[k]);
    cout<<k<<' ';
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)  cin>>l[i]>>r[i];
    preorder(1);cout<<endl;
    inorder(1);cout<<endl;
    postorder(1);
}
原文地址:https://www.cnblogs.com/TheRoadToTheGold/p/6159015.html