题目介绍
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 (≤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:
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
注解
- 我使用了C11给结构体直接初始化的很方便的操作,先把相应位置初始化-1,之后如果有就改变它的值为对应位置。
- 在我看来,本题建好二叉树很容易,对二叉树进行层序遍历和中序遍历更是基础中的基础,但是这两种遍历都需要有一个前提——就是已知根节点。
而根节点本题是没有给的,所以需要我们自己找到。
我采用的方法是:给每个结点增加父节点的存储,然后从树上随便一点一直向上寻找,走到最后就是根节点了。
代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int parent = -1; //这样子初始化是c11的东西-这样我就更省事了
int l=-1,r=-1; //没有就是-1
}p[15];
queue<int>q;
int start = 1; //调整输出形态
void inorder(int root) //中序遍历
{
if(root!=-1)
{
inorder(p[root].l);
if(start==1)
{
cout<<root;
start = 0;
}
else cout<<" "<<root;
inorder(p[root].r);
}
}
int main()
{
int N;
cin>>N;
getchar();
char l,r;
for(int i=0;i<N;i++)
{
scanf("%c %c",&l,&r);
//在这里就逆转得了
if(l!='-')
{
p[i].r = l-'0';
p[l-'0'].parent = i;
}
if(r!='-')
{
p[i].l = r-'0';
p[r-'0'].parent = i;
}
getchar();
}
//难点在于没有确定根节点在哪
//我选择增加parent,然后从某一结点向上找的方式
int index = 0;
while(p[index].parent!=-1) index = p[index].parent;
int root = index;
//层序遍历--懒得写成函数了
q.push(root);
while(q.size())
{
int pre = q.front();
if(start==1)
{
cout<<pre;
start = 0;
}
else cout<<" "<<pre;
if(p[pre].l!=-1) q.push(p[pre].l);
if(p[pre].r!=-1) q.push(p[pre].r);
q.pop();
}
cout<<endl;
start = 1;
inorder(root);
return 0;
}