zoukankan      html  css  js  c++  java
  • 3143 二叉树的序遍历codevs

    题目描述 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>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    int n;
    struct node{
        int z;
        int y;
        int j;
    }tree[1000];
    void qian(int x)
    {
        printf("%d ",tree[x].j);
        if(tree[x].z!=0)qian(tree[x].z);
        if(tree[x].y!=0)qian(tree[x].y);
    }
    
    void zhong(int x)
    {
        if(tree[x].z!=0)zhong(tree[x].z);
            printf("%d ",tree[x].j);
        if(tree[x].y!=0)zhong(tree[x].y);
    }
    
    void hou(int x)
    {
        if(tree[x].z!=0)hou(tree[x].z);
        if(tree[x].y!=0)hou(tree[x].y);
        printf("%d ",tree[x].j);
    }
    int main()
    {
        cin>>n;
        for(int i=1;i<=n;i++)
        {
            cin>>tree[i].z;
            cin>>tree[i].y;
            tree[i].j=i;
        }
        qian(1);
        cout<<endl;
        zhong(1);
        cout<<endl;
        hou(1);
        cout<<endl;
        return 0;
    }
  • 相关阅读:
    【Windows】netsh动态配置端口转发
    Python 脚本注册为Windows Service
    【Windows】Python脚本随机启动
    【MySQL】CSV 文件导入MySQL
    【Python】改变对象的字符串显示
    【Python】偏函数
    【Python】装饰器理解
    【Python】什么是闭包
    【Python】高阶函数介绍
    【Python】__all__ 暴露接口
  • 原文地址:https://www.cnblogs.com/sssy/p/6647403.html
Copyright © 2011-2022 走看看