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 <cstdio> #include <cstring> #include <iostream> #include <queue> using namespace std; const int maxn = 10 + 10; struct node { int l, r; }tn[maxn]; struct qn { int root, l, r; //要记录根节点和左右子节点信息 qn(int root, int l, int r) : root(root), l(l), r(r) {} }; char s1[5], s2[5]; int tree[maxn], N, cou; bool vis[maxn]; void build(int root, int i) { tree[i] = root; if (root == -1) return; build(tn[root].l, i * 2); build(tn[root].r, i * 2 + 1); } //层序遍历其实就是个BFS void lo(int root) { queue<qn> Q; Q.push(qn(root, 1 * 2, 1 * 2 + 1)); bool first = true; while (!Q.empty()) { qn tn = Q.front(); Q.pop(); if (first) printf("%d", tn.root); else printf(" %d", tn.root); if (first) first = false; int l = tn.l, r = tn.r; int ln = tree[l], rn = tree[r]; //右优先 if (rn != -1) { Q.push(qn(rn, r * 2, r * 2 + 1)); //注意更改左右节点信息 } if (ln != -1) { Q.push(qn(ln, l * 2, l * 2 + 1)); //注意更改左右节点信息 } } } //中序遍历其实就是个DFS void io(int root, int i) { if (root != -1) { //右子树优先 io(tn[root].r, i * 2 + 1); cou++; if (cou == 1) printf("%d", tree[i]); else printf(" %d", tree[i]); io(tn[root].l, i * 2); } } int main() { scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%s%s", s1, s2); if (s1[0] != '-') tn[i].l = atoi(s1); else tn[i].l = -1; if (s2[0] != '-') tn[i].r = atoi(s2); else tn[i].r = -1; } memset(vis, false, sizeof(vis)); for (int i = 0; i < N; i++) { if (tn[i].l != -1) vis[tn[i].l] = true; if (tn[i].r != -1) vis[tn[i].r] = true; } int root; //不是任何节点的左右子节点的那个数就是根节点 for (int i = 0; i < N; i++) { if (!vis[i]) { root = i; break; } } memset(tree, -1, sizeof(tree)); //建树 build(root, 1); lo(root); puts(""); cou = 0; io(root, 1); puts(""); return 0; }