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!
译:下面是的话来自 Max Howell @twitter:
Google: 我们 90% 的工程师都使用您编写的软件(Homebrew),但是您无法在白板上反转二叉树,所以滚蛋。
现在轮到你来证明你可以翻转一颗二叉树!
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.
译:每个输入文件包含一个测试,第一行给定一个正整数 N (≤10) 表示二叉树的总结点数目。因此节点从 0 到 N -1 进行编号。接下来N行,每行对应从 0 到 N -1 的结点,并且给定每个结点的左右孩子结点的索引。如果这个结点的孩子节点不存在,用一个 -
表示,任何一对孩子结点用空格隔开。
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.
译:对于每个测试用例,第一行输出翻转二叉树的层序遍历序列,第二行输出翻转二叉树的中序遍历序列。每个结点之间用空格隔开,并且行末没有多余的空格。
8 1 - - - 0 - 2 7 - - - - 5 - 4 6
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
首先是建树,然后就是对树进行翻转后的层序遍历和中序遍历。
#include<bits/stdc++.h> using namespace std ; typedef struct{ int father , left , right ; // 分别表示当前结点的父结点、左右孩子结点 }NODE ; NODE Node[10] ; void init(){ for(int i = 0 ; i < 10 ; i ++){ Node[i].father = i ; Node[i].left = Node[i].right = -1 ; } } int n , t ; char x , y ; int findRoot(int n){ for(int i = 0 ; i < n ; i ++) if(Node[i].father == i) return i ; return -1 ; } vector<int> level , in ; void levelInverted(int x){ if(x == -1) return ; queue<int> q ; q.push(x) ; while(!q.empty()){ int top = q.front() ; q.pop() ; level.push_back(top) ; if(Node[top].right != -1) q.push(Node[top].right) ; if(Node[top].left != -1) q.push(Node[top].left) ; } } void inOrderInverted(int x){ if(x == -1) return ; inOrderInverted(Node[x].right) ; in.push_back(x) ; inOrderInverted(Node[x].left) ; } int main(){ init() ; // 初始化 cin >> n ; for(int i = 0 ; i < n ; i ++){ cin >> x >> y ; if(x != '-') { t = x - '0' ; Node[i].left = t; Node[t].father = i ; // 将孩子结点的父节点赋值为本结点 } if(y != '-') { t = y - '0' ; Node[i].right = t; Node[t].father = i ; // 将孩子结点的父节点赋值为本结点 } } int root = findRoot(n) ; levelInverted(root) ; inOrderInverted(root) ; for(int i = 0 ; i < n ; i ++) printf("%d%c" , level[i] , ((i==n-1)?'\n':' ')) ; for(int i = 0 ; i < n ; i ++) printf("%d%c" , in[i] , ((i==n-1)?'\n':' ')) ; return 0 ; }