zoukankan      html  css  js  c++  java
  • 3143二叉树的遍历(祭奠)

    题目链接:http://www.wikioi.com/problem/3143/

    题目要求给你一个二叉树,然后进行前序,中序,后序,进行遍历。题目很简单,但是这题一开始自己理解错了,坑了好久----

    这题输入的是自己孩子的编号,不是输入孩子的值,例如给出如下的数据:

    9

    3 4

    6 9

    7 8

    2 5

    0 0

    0 0

    0 0

    0 0

    0 0

    构造成的树为:

               1

          3       4

         7   8      2   5

                             6  9

    代码:

     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 //本题不是一般的常规遍历,输入给出的是给你孩子的编号,然后进行遍历坑-----
     5 int tree[20][3];
     6 #define L 1
     7 #define R 2
     8 
     9 void tree_preorder(int i)
    10 {
    11     if(i!=0 )
    12         {
    13             printf("%d ",i);
    14             tree_preorder(tree[i][L]);
    15             tree_preorder(tree[i][R]);
    16         }
    17 }
    18 
    19 void tree_inorder(int i)
    20 {
    21      if(i!= 0)
    22         {
    23             tree_inorder(tree[i][L]);
    24              printf("%d ",i);
    25            tree_inorder(tree[i][R]);
    26         }
    27 
    28 }
    29 void tree_epilogue(int i)
    30 {
    31      if(i != 0)
    32         {
    33             tree_epilogue(tree[i][L]);
    34             tree_epilogue(tree[i][R]);
    35              printf("%d ",i);
    36         }
    37 
    38 }
    39 int main()
    40 {
    41     int n,x,y;
    42     while(~scanf("%d",&n))
    43     {
    44         memset(tree,0,sizeof(tree));
    45         for(int i = 1; i <= n; i++)
    46         {
    47             scanf("%d%d",&x,&y);
    48             tree[i][L] = x;
    49             tree[i][R] = y;
    50         }
    51     tree_preorder(1);
    52     printf("
    ");
    53     tree_inorder(1);
    54     printf("
    ");
    55     tree_epilogue(1);
    56     printf("
    ");
    57     }
    58     return 0;
    59 }
  • 相关阅读:
    编程 判断 是否满足条件 的 验证代码。
    Javascript作用域详解。
    DateTable To Json
    反射_获取字段的Description信息
    C# Json格式
    jQuery选择器
    SQL日期格式转换
    【转载】#pragma once与#ifndef
    C++中的左值与右值
    HTML、CSS基础知识
  • 原文地址:https://www.cnblogs.com/yyroom/p/3636881.html
Copyright © 2011-2022 走看看