zoukankan      html  css  js  c++  java
  • [刷题] PTA 03-树2 List Leaves

    程序:

     1 #include <stdio.h>
     2 #include <queue>
     3 #define MaxTree 20
     4 #define Null -1
     5 using namespace std;
     6 
     7 struct TreeNode {
     8     int Left;
     9     int Right;
    10 } T[MaxTree];
    11 int N,check[MaxTree];
    12 int count = 0;
    13 
    14 int BuildTree(struct TreeNode T[]) {
    15     int Root = Null,i;
    16     char cl,cr;
    17     scanf("%d
    ",&N);
    18     if(N) {
    19         for(i=0; i<N; i++) check[i]=0;
    20         for(i=0; i<N; i++) {
    21             scanf("%c %c
    ",&cl,&cr);
    22             if(cl=='-' && cr=='-') count++;
    23             if(cl!='-') {
    24                 T[i].Left = cl-'0';
    25                 check[T[i].Left]=1;
    26             } else T[i].Left=Null;
    27             if(cr!='-') {
    28                 T[i].Right = cr-'0';
    29                 check[T[i].Right]=1;
    30             } else T[i].Right=Null;
    31         }
    32         for(i=0; i<N; i++)
    33             if(!check[i]) break;
    34         Root = i;
    35     }
    36     return Root;
    37 }
    38 
    39 int main() {
    40     queue<int> Q;
    41     int R,tmp;
    42     R=BuildTree(T);
    43     if(R==Null) return 0;
    44     Q.push(R);
    45     while(!Q.empty()) {
    46         tmp = Q.front();
    47         Q.pop();
    48         if(T[tmp].Left==-1 && T[tmp].Right==-1){
    49             printf("%d",tmp);
    50             count--;
    51             if(count!=0) printf(" ");
    52         }
    53         if(T[tmp].Left!=-1) Q.push(T[tmp].Left);
    54         if(T[tmp].Right!=-1) Q.push(T[tmp].Right);
    55     }
    56     return 0;
    57 }

    分析:

    1、利用队列做层序遍历

    2、17行scanf()一开始没写 ,如果只有这一行输入没事,但后面还有scanf(),而%c又是可以识别 的,所以会导致错误,详见:

    scanf()的陷阱

    https://blog.csdn.net/ff_tt/article/details/61429268

  • 相关阅读:
    珍珠项链——容斥的应用
    协程库中 WaitGroup / CountDownLatch 实现
    简单C++线程池
    switch 比 if/else 效率更高?
    [LeetCode 264.] 丑数 II
    [LeetCode 229.] 求众数 II
    [NC41] 最长无重复子数组
    [NC105] 二分查找-II
    高楼扔鸡蛋
    C++ 编译期计算
  • 原文地址:https://www.cnblogs.com/cxc1357/p/10809287.html
Copyright © 2011-2022 走看看