PAT_A1102#Invert a Binary Tree
Source:
Description:
The following is from Max Howell @twitter:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.
Now it's your turn to prove that YOU CAN invert a binary tree!
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a
-
will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8 1 - - - 0 - 2 7 - - - - 5 - 4 6
Sample Output:
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
Keys:
Code:
1 /* 2 time: 2019-06-30 14:09:56 3 problem: PAT_A1102#Invert a Binary Tree 4 AC: 23:00 5 6 题目大意: 7 打印镜像树层序和中序遍历 8 输入: 9 第一行给出,结点数N<=10 10 接下来N行,结点i(0~n-1)的左孩子和右孩子 11 12 基本思路: 13 构造静态树遍历 14 */ 15 #include<cstdio> 16 #include<queue> 17 #include<string> 18 #include<iostream> 19 using namespace std; 20 const int M=1e2; 21 int mp[M]={0},n; 22 struct node 23 { 24 int lchild,rchild; 25 }tree[M]; 26 27 void LayerOrder(int root) 28 { 29 queue<int> q; 30 q.push(root); 31 int pt=0; 32 while(!q.empty()) 33 { 34 root = q.front(); 35 q.pop(); 36 printf("%d%c", root, ++pt==n?'\n':' '); 37 if(tree[root].rchild != -1) 38 q.push(tree[root].rchild); 39 if(tree[root].lchild != -1) 40 q.push(tree[root].lchild); 41 } 42 } 43 44 void InOrder(int root) 45 { 46 if(root == -1) 47 return; 48 static int pt=0; 49 InOrder(tree[root].rchild); 50 printf("%d%c", root, ++pt==n?'\n':' '); 51 InOrder(tree[root].lchild); 52 } 53 54 int main() 55 { 56 #ifdef ONLINE_JUDGE 57 #else 58 freopen("Test.txt", "r", stdin); 59 #endif // ONLINE_JUDGE 60 61 scanf("%d", &n); 62 string r,l; 63 for(int i=0; i<n; i++){ 64 cin >> l >> r; 65 if(l == "-") 66 tree[i].lchild = -1; 67 else{ 68 tree[i].lchild = atoi(l.c_str()); 69 mp[tree[i].lchild]=1; 70 } 71 if(r == "-") 72 tree[i].rchild = -1; 73 else{ 74 tree[i].rchild = atoi(r.c_str()); 75 mp[tree[i].rchild]=1; 76 } 77 } 78 int root; 79 for(int i=0; i<n; i++) 80 if(mp[i]==0) 81 root=i; 82 LayerOrder(root); 83 InOrder(root); 84 85 return 0; 86 }