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:从数据结果的反馈来看,建树是从右到左的;
要求2:考虑只有一个节点的情况。
程序步骤:
第一步、建树;
第二步、层次遍历并输出;
第三步、中序遍历并输出。
具体程序(AC)如下:
#include <iostream>
#include <queue>
using namespace std;
struct node{
int left;
int right;
};
node tree[15];
int parent[15];
queue<int> q;
vector<int> inOrderResult;
void levelOrder(int root){
while(!q.empty()){
q.pop();
}
q.push(root);
int tmp;
while(!q.empty()){
tmp=q.front();
if(tmp==root)
cout<<tmp;
else
cout<<" "<<tmp;
q.pop();
if(tree[tmp].left!=-1)
q.push(tree[tmp].left);
if(tree[tmp].right!=-1)
q.push(tree[tmp].right);
}
cout<<endl;
}
void inOrder(int root){
if(root==-1)
return;
inOrder(tree[root].left);
inOrderResult.push_back(root);
inOrder(tree[root].right);
}
int main(int argc, char const *argv[])
{
/* code */
int num;
cin>>num;
int i;
char a,b;
for(i=0;i<num;++i)
parent[i]=-1;
for(i=0;i<num;++i)
{
cin>>a>>b;//根据题意,数字只有个位数,只需要一个char即可
if(a=='-')
tree[i].right=-1;
else
{
tree[i].right=a-'0';
parent[a-'0']=i;
}
if(b=='-')
tree[i].left=-1;
else
{
tree[i].left=b-'0';
parent[b-'0']=i;
}
}
int root=-1;
for(i=0;i<num;++i)
if(parent[i]==-1)
{
root=i;
break;
}
levelOrder(root);
inOrder(root);
for(i=0;i<inOrderResult.size()-1;++i)
{
cout<<inOrderResult[i]<<" ";
}
if(inOrderResult.size()>=1){
cout<<inOrderResult[inOrderResult.size()-1]<<endl;
}
return 0;
}