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 1 6 5 7 4 3 2 0 1
這道題主要考察level order和in order遍歷樹,至於反轉二叉樹倒不是關鍵(只要在建立二叉樹的時候把輸入的左子樹當成右子樹,右子樹當成左子樹即可)。
另外由於序號已知,所以可以直接用int來代替指針指向child或parent。
level order遍歷用隊列來完成,in order用遞歸即可, 代碼如下:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef struct n{
int id;
int parent;
int leftChild;
int rightChild;
n(){
parent = leftChild = rightChild = -1;
}
}node;
vector<node> tree;
int root;
bool flag;
void levelorder(int root){
queue<int> treeQueue;
treeQueue.push(root);
while(!treeQueue.empty()){
int node = treeQueue.front();
treeQueue.pop();
if(tree[node].leftChild != -1)
treeQueue.push(tree[node].leftChild);
if(tree[node].rightChild != -1)
treeQueue.push(tree[node].rightChild);
if(node == root)
cout<<node;
else
cout<<" "<<node;
}
cout<<endl;
}
int findRoot(){
int k = 0;
while(tree[k].parent != -1){
k = tree[k].parent;
}
return k;
}
void inorder(int x){
if(x == -1)
return;
inorder(tree[x].leftChild);
if(flag)
cout<<" "<<x;
else{
cout<<x;
flag = true;
}
inorder(tree[x].rightChild);
}
int main(void)
{
int N;
cin>>N;
tree.resize(N);
for(int i = 0; i < N; i++){
string str[2];
cin>>str[0]>>str[1];
tree[i].id = i;
if(str[0][0]!='-'){
tree[i].rightChild = atoi(str[0].c_str());
tree[atoi(str[0].c_str())].parent = i;
}
if(str[1][0]!='-'){
tree[i].leftChild = atoi(str[1].c_str());
tree[atoi(str[1].c_str())].parent = i;
}
}
root = findRoot();
levelorder(root);
flag = false;
inorder(root);
cout<<endl;
return 0;
}