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

    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

     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int m;
     5 struct k{
     6     int n,l,r;
     7 }tree[1000];
     8 void qian(int x)
     9 {
    10     printf("%d ",tree[x].n);
    11     if(tree[x].l)
    12      {
    13          qian(tree[x].l);
    14      }
    15      if(tree[x].r)
    16       {
    17           qian(tree[x].r);
    18       }
    19 }
    20 void zhong(int x)
    21 {
    22     if(tree[x].l)
    23      {
    24          zhong(tree[x].l);
    25      }
    26      printf("%d ",tree[x].n);
    27      if(tree[x].r)
    28       {
    29           zhong(tree[x].r);
    30       }
    31 }
    32 void hou(int x)
    33 {
    34     if(tree[x].l)
    35     {
    36         hou(tree[x].l);
    37     }
    38     if(tree[x].r)
    39     {
    40         hou(tree[x].r);
    41     }
    42     printf("%d ",tree[x].n);
    43 }
    44 int main()
    45 {
    46     cin>>m;
    47     for(int i=1;i<=m;i++)
    48      {
    49          scanf("%d%d",&tree[i].l,&tree[i].r);
    50          tree[i].n=i;
    51      }
    52      qian(1);
    53      printf("
    ");
    54      zhong(1);
    55      printf("
    ");
    56      hou(1);
    57      printf("
    ");
    58      return 0;
    59 }
  • 相关阅读:
    [php]php设计模式 (总结)
    MySql常用命令总结
    mysql常用命令
    搜集几个API接口
    c语言 11-7
    c语言中转换字符串函数 atoi函数
    c语言中 strncmp函数, 函数原型和头文件。
    c语言中strcmp函数,函数原型和函数头文件
    c语言中strncat函数,函数原型以头文件
    c语言中strcat函数,函数原型和函数头文件
  • 原文地址:https://www.cnblogs.com/lyqlyq/p/6648550.html
Copyright © 2011-2022 走看看