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
思路
1.题目要求左右颠倒二叉树,并按层次遍历和中序遍历输出。那么其实只要在构造树的时候交换下输入数据就可以直接构造出一颗颠倒后的树了。
2.输出的时候需要注意空格,对于两种遍历的输出只要特殊标识下第一次的输出就行了。
代码
#include<iostream> #include<vector> #include<queue> using namespace std; class Node { public: int left; int right; int value; }; vector<Node> btree(10); int createTree(const int& N) { vector<bool> roots(N,true); for(int i = 0;i < N ;i++) { char l,r; cin >> l >> r; btree[i].value = i; //invert left if(l != '-') { btree[i].right = l - '0'; roots[l-'0'] = false; } else btree[i].right = -1; //invert right if(r != '-') { btree[i].left = r - '0'; roots[r-'0'] = false; } else btree[i].left = - 1; } int root = 0; for(int i = 0;i < N;i++) { if(roots[i] == true) { root = i; break; } } return root; } void bfs(int root) { queue<int> q; q.push(root); while(!q.empty()) { int cur = q.front(); q.pop(); if(cur == root) cout << cur; else cout << " " << cur; if(btree[cur].left != - 1) q.push(btree[cur].left); if(btree[cur].right != -1) q.push(btree[cur].right); } cout << endl; } int firstput = 0; void inorder(int root) { if(root == -1) return; if(btree[root].left != -1) inorder(btree[root].left); if( firstput++ == 0) cout << root; else cout << " " <<root; if(btree[root].right != -1) inorder(btree[root].right); } int main() { int N; while(cin >> N) { int root = createTree(N); bfs(root); inorder(root); } }