树 先序中序后序遍历

题目链接:http://codevs.cn/problem/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

AC代码:

 

 

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
struct node
{
    int left,right;
}tree[105];

void _for(int m)
{
    if(!m)
        return;
    cout<<m<<" ";
    _for(tree[m].left);
    _for(tree[m].right);
}
void _mid(int m)
{
    if(!m)
        return;
    _mid(tree[m].left);
    cout<<m<<" ";
    _mid(tree[m].right);
}
void _last(int m)
{
    if(!m)
        return ;
    _last(tree[m].left);
    _last(tree[m].right);
    cout<<m<<" ";
}
int main()
{
    int n;
    cin>>n;
    memset(tree,0,sizeof(tree));
    for(int i=1;i<=n;i++)
        cin>>tree[i].left>>tree[i].right;
    _for(1);
    cout<<endl;
    _mid(1);
    cout<<endl;
    _last(1);
    cout<<endl;
    return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值