1102 Invert a Binary Tree25 分

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 (≤) 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<iostream>
 2 #include<vector>
 3 #include<queue>
 4 using namespace std;
 5 vector<vector<int> > v(10);
 6 vector<int> in,exist(10,1),level;
 7 
 8 void inorder(int root){
 9   if(root==-1) return;//先遍历右子树再遍历左子树
10   if(v[root][1]!=-1) inorder(v[root][1]);
11   in.push_back(root);
12   if(v[root][0]!=-1) inorder(v[root][0]);
13 }
14 
15 int main(){
16   int n,i,root,left,right;
17   char l,r;
18   scanf("%d",&n);
19   for(i=0; i<n; i++){
20     cin>>l>>r;
21     left = l==- ? -1 : l-0;
22     right = r==- ? -1 : r-0;
23     if(left>=0) exist[left]=0;
24     if(right>=0) exist[right]=0;
25     v[i].push_back(left); v[i].push_back(right);
26   }
27   for(i=0; i<n; i++) if(exist[i]) root=i;
28   queue<int> q;
29   q.push(root);
30   while(q.size()){
31     int temp=q.front();
32     q.pop();
33     level.push_back(temp);
34     if(v[temp][1]!=-1) q.push(v[temp][1]);
35     if(v[temp][0]!=-1) q.push(v[temp][0]);
36   }
37   inorder(root);
38   printf("%d",level[0]);
39   for(i=1; i<n; i++) printf(" %d",level[i]);
40   printf("\n%d",in[0]);
41   for(i=1; i<n; i++) printf(" %d",in[i]);
42   return 0;
43 }

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...