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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。