Topic Information
1102. Invert a Binary Tree (25)
Time limit MS
Memory Limit 65536 KB
Code length limit 16000 B
The following is from Max Howell @twitter:
google:90% of our engineers with the software you wrote (Homebrew), but can ' t invert a binary tree on a whiteboard so Fuck off.
Now it's your turn to prove so CAN invert a binary tree!
Input Specification:
Each input file contains the one test case. For each case, the first line gives a positive integer N (<=10) which are the total number of nodes in the Tree–and he nCE the nodes is 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 Node. If the child does not exist, a "-" 'll be put on the position. Any pair of children is separated by a space.
Output Specification:
For each test case, print in the first line of the Level-order, and then on the second line the In-order traversal sequences of the inverted tree. There must is 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
Thinking of solving problems
Binary Tree Traversal
AC Code
#include <cstdio>#include <vector>#include <set>using namespace STD; vector<int>level[ the]; vector<int>Inorder;intGet () {Chars[Ten];scanf('%s ', s);if(s[0] =='-')return-1;intAsscanf(S,"%d", &a);returnA;}intl[ the], r[ the];voidInorder (intRoot) {if(R[root]! =-1) inorder (R[root]); Inorder.push_back (root);if(L[root]! =-1) inorder (L[root]);}voidLevelorder (intRootintLV) {level[lv].push_back (root);if(R[root]! =-1) Levelorder (R[root], LV +1);if(L[root]! =-1) Levelorder (L[root], LV +1);}intMain () {intNscanf("%d", &n); Set<int>St for(inti =0; I < n; ++i) {St.insert (i); } for(inti =0; I < n; ++i) {L[i] = get (); R[i] = get ();if(L[i]! =-1) St.erase (L[i]);if(R[i]! =-1) St.erase (R[i]); } levelorder (*st.begin (),0); Inorder (*st.begin ());printf("%d", *st.begin ()); for(inti =1; I < the; ++i) { for(intj =0; J < Level[i].size (); ++J) {printf("%d", Level[i][j]); } }printf("\n%d", inorder[0]); for(inti =1; I < inorder.size (); ++i) {printf("%d", Inorder[i]); }return 0;}
1102. Invert a binary tree (25) "Binary Trees"--pat (Advanced level) practise