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 6Sample Output:
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
#include<iostream> #include<vector> #include<cstring> #include<queue> #include<algorithm> using namespace std; int t[102][2]; int n; char x[2];char y[2]; int flag[101];//标记是否是根结点 int rt; //因为有的结点是零下标,所以叶子的儿子都设为一个负值 int tag; //中序遍历 void dfs(int x){ if(x==-1)return; dfs(t[x][0]); printf("%s%d",tag?" ":"\n",x);tag=1; dfs(t[x][1]); } //前序顺序 反转 这棵树 void invert(int x){ if(x<0)return; swap(t[x][0],t[x][1]); invert(t[x][0]); invert(t[x][1]); } int main(){ cin>>n; //建树,以及标记非根节点 for(int i=0;i<n;i++){ cin>>x>>y; t[i][0]=(x[0]=='-'?-1:x[0]-'0');flag[t[i][0]]=1; t[i][1]=(y[0]=='-'?-1:y[0]-'0');flag[t[i][1]]=1; } queue<int>q; //寻找根节点 for(int i=0;i<n;i++){ if(flag[i])continue; else{ rt=i; q.push(i); break; } } //反转一棵树 invert(rt); while(!q.empty()){ int tt=q.front();q.pop(); printf("%s%d",flag[tt]==1?" ":"",tt); if(t[tt][0]!=-1)q.push(t[tt][0]); if(t[tt][1]!=-1)q.push(t[tt][1]); } dfs(rt); return 0; }