A1102 Invert a Binary Tree (25 point(s))

中序 层序

1. 原文

The following is from Max Howell @twitter:

1
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 (≤10) 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:

1
2
3
4
5
6
7
8
9
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample output:

1
2
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

2. 解析

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int lchild,rchild;
}v[20];
char c1[5],c2[5];
int getnum(char c[]){
int num=0;
for (int i = 0; c[i] != '\0'; ++i)
{
num=num*10+c[i]-'0';
}
return num;
}
int indegree[30]={};

void inorder(int root,vector<int> &in){
if (root==-1)
{
return;
}
inorder(v[root].rchild,in);
in.push_back(root);
inorder(v[root].lchild,in);
}

void levelorder(int root,vector<int> &level){
queue<int> q;
q.push(root);
while(!q.empty()){
int temp=q.front();
level.push_back(temp);
q.pop();
if (v[temp].rchild!=-1)
{
q.push(v[temp].rchild);
}
if (v[temp].lchild!=-1)
{
q.push(v[temp].lchild);
}
}
}

int main()
{
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%s%s",c1,c2);
if (c1[0]=='-')
{
v[i].lchild=-1;
}else{
v[i].lchild=getnum(c1);
indegree[getnum(c1)]++;
}
if (c2[0]=='-')
{
v[i].rchild=-1;
}else{
v[i].rchild=getnum(c2);
indegree[getnum(c2)]++;
}
}
int root=0;
for (int i = 0; i < n; ++i)
{
if (indegree[i]==0)
{
root=i;
break;
}
}
vector<int> in,level;
inorder(root,in);
levelorder(root,level);
for (int i = 0; i < n; ++i)
{
printf("%d",level[i]);
if (i<n-1)
{
printf(" ");
}else{
printf("\n");
}
}
for (int i = 0; i < n; ++i)
{
printf("%d",in[i]);
if (i<n-1)
{
printf(" ");
}else{
printf("\n");
}
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1102/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!