zoukankan      html  css  js  c++  java
  • 九度oj 题目1184:二叉树遍历

    题目描述:

    编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。
    例如如下的先序遍历字符串:
    ABC##DE#G##F###
    其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

    输入:

    输入包括1行字符串,长度不超过100。

    输出:

    可能有多组测试数据,对于每组数据,
    输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
    每个输出结果占一行。

    样例输入:
    abc##de#g##f###
    样例输出:
    c b e g d f a 

     1 #include <cstdio>
     2 #include <cstring>
     3 
     4 int left[300];
     5 int right[300];
     6 int par[300];
     7 
     8 char str[102];
     9 
    10 void middleOut(int root) {
    11     int lr = left[root];
    12     if(lr != -1) {
    13         middleOut(lr);
    14     }
    15     printf("%c ",root);
    16     int rr = right[root];
    17     if(rr != -1) {
    18         middleOut(rr);
    19     }
    20 }
    21 int main(int argc, char const *argv[])
    22 {
    23     while(scanf("%s",str) != EOF) {
    24         if(str[0] == '#') {
    25             continue;
    26         }
    27         for(int i = 0; i < 300; i++) {
    28             left[i] = -1;
    29             right[i] = -1;
    30             par[i] = -1;
    31         }
    32         int root = str[0];
    33         int len = strlen(str);
    34         int father = root;
    35         int state =0;
    36         for(int i = 1; i < len; i++) {
    37             if(str[i] != '#') {
    38                 if(state == 0) {
    39                     left[father] = str[i];
    40                     par[str[i]] = father;
    41                     father = str[i];
    42                 }
    43                 else if(state == 1) {
    44                     right[father] = str[i];
    45                     par[str[i]] = father;
    46                     father = str[i];
    47                     state = 0;
    48                 }
    49             }
    50             else if(str[i] == '#') {
    51                 if(state == 0) {
    52                     state = 1;
    53                 }
    54                 else if(state == 1) {
    55                     father = par[father];
    56                     while(right[father] != -1) {
    57                         father = par[father];
    58                     }
    59                 }
    60             }
    61         }
    62         middleOut(root);
    63         puts("");
    64     }    
    65     return 0;
    66 }
  • 相关阅读:
    LeetCode 189. Rotate Array
    LeetCode 965. Univalued Binary Tree
    LeetCode 111. Minimum Depth of Binary Tree
    LeetCode 104. Maximum Depth of Binary Tree
    Windows下MySQL的安装与配置
    LeetCode 58. Length of Last Word
    LeetCode 41. First Missing Positive
    LeetCode 283. Move Zeroes
    《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》读后感
    删除docker下的镜像
  • 原文地址:https://www.cnblogs.com/jasonJie/p/5866543.html
Copyright © 2011-2022 走看看