PAT 1102. Invert a Binary Tree (25)

来源:互联网 发布:数字互动沙盘软件 编辑:程序博客网 时间:2024/05/23 00:53

1102. Invert a Binary Tree (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
3 7 2 6 4 0 5 16 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;elsecout<<" "<<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;}

 

0 0
原创粉丝点击