3143 二叉树的序遍历codevs

3143 二叉树的序遍历

 

 时间限制: 1 s
 空间限制: 32000 KB
 题目等级 : 白银 Silver
 
 
 
题目描述 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


#include<iostream>
using namespace std;
int a[17][2];
int n;
void F(int x)
{
    cout << x << " ";
    if(a[x][0])
      F(a[x][0]);
    if(a[x][1])
      F(a[x][1]);
}

void M(int x)
{
    if(a[x][0])
      M(a[x][0]);
    cout << x << " ";
    if(a[x][1])
      M(a[x][1]);
}

void B(int x)
{
    if(a[x][0])
      B(a[x][0]);
    if(a[x][1])
      B(a[x][1]);
    cout << x << " ";
}
int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
        cin >> a[i][0] >> a[i][1];
    F(1);
    cout << endl;
    M(1);
    cout << endl;
    B(1);
    cout << endl;
}
原文地址:https://www.cnblogs.com/denghui666/p/7857837.html