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 16 5 7 4 3 2 0 1
这个题目已经将二叉树的结构信息给出了,题目的重点应该是在于invert,但是如果采用vector来保存节点的孩子信息,那么就不需要进行特意的Invert了,只要在遍历的时候,将vector中存储的两个孩子节点代表的意思取反即可,即将第一个作为右孩子,将第二个作为左孩子。然后就是使用广度优先搜索逐层打印信息,在使用中序遍历即可。
#include <iostream> #include <map> #include <vector> #include <queue> using namespace std; map<int,vector<int> >tree; vector<int> inor; void bfs(int root); void iner_traversal(int root); int main() { int n; cin >>n; char tmp; //输出二叉树的节点关系信息,并且找到根节点 int root_num; vector<int> record(n,0); for(int i=0;i<n;i++) { for(int j=0;j<2;j++) { cin >>tmp; if(tmp=='-') tree[i].push_back(-1); else { tree[i].push_back(tmp-'0'); record[tmp-'0']++; } } } vector<int>::iterator iter=record.begin(); int i=0; for(;iter!=record.end();iter++,i++) if(*iter!=1) root_num=i; //广度优先搜索,逐层打印信息 bfs(root_num); //中序遍历,将数值进行存储 iner_traversal(root_num); //中序遍历结果输出 iter=inor.begin(); cout <<*iter; iter++; for(;iter!=inor.end();iter++) cout <<" " <<*iter; cout <<endl; return 0; } void bfs(int root) { queue<int> q; q.push(root); bool flag=true; while(!q.empty()) { int tmp=q.front(); q.pop(); if(flag) { cout <<tmp; flag=false; } else cout <<" "<<tmp; if(tree[tmp].at(1)!=-1) q.push(tree[tmp].at(1)); if(tree[tmp].at(0)!=-1) q.push(tree[tmp].at(0)); } cout <<endl; } void iner_traversal(int root) { if(tree[root].at(1)!=-1) iner_traversal(tree[root].at(1)); inor.push_back(root); if(tree[root].at(0)!=-1) iner_traversal(tree[root].at(0)); }
本文详细阐述了如何通过广度优先搜索和中序遍历来实现二叉树的反转操作,包括输入输出规范及代码实现。
313

被折叠的 条评论
为什么被折叠?



