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
题目意思....emmm 刚开始看不在在ght在提示下...嗯 3没有出现3是跟然后就这么找下去
之后输出 反转后的层序遍历和中序遍历
代码:
#include<bits/stdc++.h>
using namespace std;
vector<int>vec,level;
struct node
{
int data;
int left,right;
}root[15];
struct Node
{
int data;
Node *left,*right;
}*tree;
int digit[15];
Node* BuildTree(int x)
{
Node *tmp = new Node();
tmp->data = x;
tmp->left = tmp->right = NULL;
if(root[x].left != -1)
tmp->left = BuildTree(root[x].left);
if(root[x].right != -1)
tmp->right = BuildTree(root[x].right);
return tmp;
}
void InvertInorter(Node* root)
{
if(root)
{
InvertInorter(root->right);
vec.push_back(root->data);
InvertInorter(root->left);
}
}
void LevelOrder(Node* tree)
{
queue<Node*>qu;
qu.push(tree);
while(qu.empty()==0)
{
Node* tmp = qu.front();
qu.pop();
level.push_back(tmp->data);
if(tmp->right!=NULL)
qu.push(tmp->right);
if(tmp->left!=NULL)
qu.push(tmp->left);
}
return ;
}
int main()
{
int n;
scanf("%d",&n);
getchar();
char str[5];
for(int i = 0 ; i < n; i++)
{
//scanf("%[^\n]",str);
//gets(str);
fgets(str,5,stdin);//stdin键盘输
root[i].data = i;
if(str[0]>='0' && str[0] <='9')
{
root[i].left = str[0]-'0';
digit[str[0] - '0']++;
}
else
root[i].left = -1;
if(str[2]>='0' && str[2] <='9')
{
root[i].right = str[2]-'0';
digit[str[2] - '0']++;
}
else
root[i].right = -1;
}
//找根
int top = -1;
for(int i = 0 ; i < n;i ++)
{
if(digit[i] == 0)
{
top = i;
break;
}
}
//找到根之后就可以开始建树
tree = BuildTree(top);
//层序
LevelOrder(tree);
for(int i = 0 ; i < n; i ++)
printf("%d%c",level[i]," \n"[i==n-1]);
//翻转
InvertInorter(tree);
for(int i = 0 ; i < n; i ++)
printf("%d%c",vec[i]," \n"[i==n-1]);
return 0;
}