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
题意:
告诉你一棵树,让你输出他的镜像后的 中序遍历和层序遍历
思路:
只需要在遍历过程中先右子树再左子树即可完成
//N个结点 从0到n-1
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100;
struct Node
{
int lchild,rchild;
}node[maxn];
vector<int>inans,levelans;
void mirlevelorder(int root) //镜像的程序
{
queue<int>q;
q.push(root);
while(!q.empty())
{
int u=q.front();
q.pop();
levelans.push_back(u);
if(node[u].rchild!=-1) //注意这里是u 且是!=-1
q.push(node[u].rchild);
if(node[u].lchild!=-1)
q.push(node[u].lchild);
}
}
void mirinorder(int root) //镜像的中序
{
if(root==-1)
return;
mirinorder(node[root].rchild); //先走右
inans.push_back(root);
mirinorder(node[root].lchild);//再输走左
}
bool vis[maxn]={false};
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
string s1,s2;
cin>>s1>>s2;
char a,b;
a=s1[0];
b=s2[0];
// cout<<a<<"x"<<b<<endl;
if(isdigit(a))
node[i].lchild=a-'0';
else
node[i].lchild=-1;
if(isdigit(b))
node[i].rchild=b-'0';
else
node[i].rchild=-1;
if(node[i].lchild!=-1)
vis[node[i].lchild]=true;
if(node[i].rchild!=-1)
vis[node[i].rchild]=true; //建树输入数据麻烦了一点
}
int root;
for(int i=0;i<n;i++)
{
if(vis[i]==false)
{
root=i;
break;
}//找根节点
}
mirlevelorder(root);
//cout<<levelans.size()<<endl;
for(int i=0;i<levelans.size();i++)
{
printf("%d",levelans[i]);
if(i<levelans.size()-1)
printf(" ");
}
printf("\n");
mirinorder(root);
for(int i=0;i<inans.size();i++)
{
printf("%d",inans[i]);
if(i<inans.size()-1)
printf(" ");
}
//cout<<root;
}