zoukankan      html  css  js  c++  java
  • 【PAT甲级】1102 Invert a Binary Tree (25 分)(层次遍历和中序遍历)

    题意:

    输入一个正整数N(<=10),接着输入0~N-1每个结点的左右儿子结点,输出这颗二叉树的反转的层次遍历和中序遍历。

    AAAAAccepted code:

     1 #define HAVE_STRUCT_TIMESPEC
     2 #include<bits/stdc++.h>
     3 using namespace std;
     4 int a[17][5];
     5 bool vis[15];
     6 void bfs(int r){
     7     queue<int>q;
     8     q.push(r);
     9     cout<<r;
    10     while(!q.empty()){
    11         int now=q.front();
    12         q.pop();
    13         if(a[now][0]!=-1){
    14             cout<<" ";
    15             cout<<a[now][0];
    16             q.push(a[now][0]);
    17         }
    18         if(a[now][1]!=-1){
    19             cout<<" ";
    20             cout<<a[now][1];
    21             q.push(a[now][1]);
    22         }
    23     }
    24 }
    25 int flag=0;
    26 void dfs(int r){
    27     if(a[r][0]!=-1)
    28         dfs(a[r][0]);
    29     if(flag)
    30         cout<<" ";
    31     cout<<r;
    32     flag=1;
    33     if(a[r][1]!=-1)
    34         dfs(a[r][1]);
    35 }
    36 int main(){
    37     ios::sync_with_stdio(false);
    38     cin.tie(NULL);
    39     cout.tie(NULL);
    40     for(int i=0;i<10;++i)
    41         a[i][0]=a[i][1]=-1;
    42     int n;
    43     cin>>n;
    44     for(int i=0;i<n;++i){
    45         char x;
    46         cin.ignore();
    47         cin>>x;
    48         cin.ignore();
    49         if(x!='-')
    50             a[i][1]=x-'0',vis[x-'0']=1;
    51         char y;
    52         cin>>y;
    53         if(y!='-')
    54             a[i][0]=y-'0',vis[y-'0']=1;
    55     }
    56     int root=0;
    57     for(int i=0;i<n;++i)
    58         if(!vis[i])
    59             root=i;
    60     bfs(root);
    61     cout<<"
    ";
    62     dfs(root);
    63     return 0;
    64 }
    保持热爱 不懈努力 不试试看怎么知道会失败呢(划掉) 世上无难事 只要肯放弃(划掉)
  • 相关阅读:
    HashMap底层实现原理(JDK1.8)源码分析
    JVM总结
    初识Nosql
    线程池总结
    Linux中常用操作命令
    JAVA—集合框架
    TeKtronix TDS210数字示波器使用简介
    硬盘的物理结构
    Unicode 与 UTF
    I2C串行总线
  • 原文地址:https://www.cnblogs.com/ldudxy/p/11972744.html
Copyright © 2011-2022 走看看