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 was the total number of nodes in the tree--and H Ence 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:
Bayi---0-2 7----5-4 6
Sample Output:
3 7 2 6 4 0 5 16 5 7 4 3 2 0 1
1#include <stdio.h>2#include <string>3#include <iostream>4#include <string.h>5#include <sstream>6#include <vector>7#include <map>8#include <stdlib.h>9#include <queue>Ten using namespacestd; One A structnode - { -Node (): L (-1), R (-1){} the intL,r,id; - }; - -Node tree[ the]; + BOOLnotroot[ the]; - BOOLFIR =1; + voidInoder (introot) A { at if(TREE[ROOT].L! =-1) - { - Inoder (TREE[ROOT].L); - } - if(FIR) - { inFIR =0; -printf"%d", root); to } + Elseprintf"%d", root); - if(TREE[ROOT].R! =-1) the { * Inoder (TREE[ROOT].R); $ }Panax Notoginseng } - intMain () the { + intN,tem; A Charl[5],r[5]; thescanf"%d",&n); + for(inti =0; I <n;++i) - { $Tree[i].id =i; $ } - for(inti =0; I <n;++i) - { thescanf"%s%s", r,l); - if(l[0] !='-')Wuyi { theTEM =atoi (l); -TREE[I].L =tem; WuNotroot[tem] =1; - } About if(r[0] !='-') $ { -TEM =atoi (r); -TREE[I].R =atoi (r); -Notroot[tem] =1; A } + } the intRoot; - for(inti =0; I <n;++i) $ { the if(!Notroot[i]) the { theRoot =i; the Break; - } in } theQueue<node>QQ; the Qq.push (Tree[root]); About BOOLFir2 =1; the while(!qq.empty ()) the { theNode Ntem =Qq.front (); + Qq.pop (); - if(FIR2) the {BayiFir2 =0; theprintf"%d", ntem.id); the } - Elseprintf"%d", ntem.id); - if(NTEM.L! =-1) the { the Qq.push (TREE[NTEM.L]); the } the if(NTEM.R! =-1) - { the Qq.push (TREE[NTEM.R]); the } the }94printf"\ n"); the Inoder (root); theprintf"\ n"); the return 0;98}
1102. Invert a Binary Tree (25)