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
思路: 这个题目的难点是寻找树根,我的办法是使用dfs,从哪一个结点出发能够访问到所有的结点,那么该结点就是树根。可以认为存储的是一个有n-1条边的有向图,只有从根节点出发才能到达所有的结点。然后使用后序遍历进行镜像反转,按层序和后序输出即可。
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<string> #include<map> #include<set> using namespace std; vector<int> visited; struct Node { int lchild,rchild; }; Node node[11]; void findRoot(int root) { if(root==-1) return; visited.push_back(root); findRoot(node[root].lchild); findRoot(node[root].rchild); } void invert(int root) { if(root!=-1) { invert(node[root].lchild); invert(node[root].rchild); swap(node[root].lchild,node[root].rchild); } } void levelOrder(int root) { queue<int>qu; qu.push(root); cout<<root; while(!qu.empty()) { int temp=qu.front(); qu.pop(); if(node[temp].lchild!=-1) { qu.push(node[temp].lchild); cout<<" "<<node[temp].lchild; } if(node[temp].rchild!=-1) { qu.push(node[temp].rchild); cout<<" "<<node[temp].rchild; } } } vector<int> in_order; void inOrder(int root) { if(root!=-1) { inOrder(node[root].lchild); in_order.push_back(root); inOrder(node[root].rchild); } } int main() { int n; cin>>n; for(int i=0;i<n;i++) { string temp1,temp2; cin>>temp1>>temp2; if(temp1[0]==‘-‘) node[i].lchild=-1; else node[i].lchild=atoi(temp1.c_str()); if(temp2[0]==‘-‘) node[i].rchild=-1; else node[i].rchild=atoi(temp2.c_str()); } int i; for(i=0;i<n;i++) { findRoot(i); if(visited.size()==n) break; else visited.clear(); } //cout<<i<<endl; invert(i); levelOrder(i); inOrder(i); cout<<endl; cout<<in_order[0]; for(int i=1;i<in_order.size();i++) cout<<" "<<in_order[i]; return 0; }
原文地址:https://www.cnblogs.com/zhanghaijie/p/10306358.html