1102 Invert a Binary Tree(25 分)
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
解题思路:这里中序遍历和层序遍历都基本上没什么变化,主要是怎么存储这个树节点,怎么找出根节点,这里用到结构,来存储左右孩子节点,当输入的是‘-‘将其赋值为-1,如果是数字就转化存入数字,我们还要找出根节点,只要它不是其他孩子的节点,也就是在输入的这里没有出现过就是根节点。层序遍历和中序遍历我就不多说啦。
#include<bits/stdc++.h>
using namespace std;
struct node{
int left,right;
};
vector<node>no;
int flag=0;//控制输出格式
void inOrder(int root)//中序遍历
{
if(no[root].left==-1&&no[root].right==-1)
{
printf("%s%d",flag==0?"":" ",root);
flag=1;//我这里忘记flag赋值为1,导致一个测试点格式错误
return;
}
if(no[root].left!=-1) inOrder(no[root].left);
printf("%s%d",flag==0?"":" ",root);
flag=1;
if(no[root].right!=-1) inOrder(no[root].right);
}
int main(void)
{
int n;
scanf("%d",&n);getchar();//忘了getchar()
no.resize(n);//要规定大小,才可以用下标输入数据
vector<int>mark(n);//要规定大小,要不然值输不进去 ,这个用来找出根节点
for(int i=0;i<n;i++)
{
char c,d;
scanf("%c %c",&c,&d);getchar();//记得getchar()
no[i].right=(c=='-'?-1:(c-'0'));
no[i].left=(d=='-'?-1:(d-'0'));
if(no[i].left!=-1) mark[no[i].left]=1;
if(no[i].right!=-1) mark[no[i].right]=1;
}
int root;
for(int i=0;i<n;i++)
{
if(mark[i]==0)
{
root=i;
break;
}
}
queue<int> q;
q.push(root);
vector<int>level;
while(!q.empty())//层序遍历
{
int i=q.front();
q.pop();
if(no[i].left!=-1)
q.push(no[i].left);
if(no[i].right!=-1)
q.push(no[i].right);
level.push_back(i);
}
int flag1=0;
for(int i = 0; i < n; i++)
{
printf("%s%d", flag1==0?"":" ",level[i]);
flag1=1;
}
cout<<endl;
inOrder(root);
return 0;
}