根据两种遍历方式建立二叉树
层遍历二叉树
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
来源: <http://www.patest.cn/contests/pat-a-practise/1020>
#include<iostream>
#include<queue>
using namespace std;
int a[32], b[32];
struct Node {
int val;
Node *left;
Node *right;
};
Node* BuildTree(int *da,int *db,int n) {
int i, j;
if (n <= 0)
return NULL;
for (i = 0; i < n; i++) {
if (*(db + i) == *(da + n - 1))
break;
}
//important
Node *nodeTemp = (Node*)malloc(sizeof(Node));
nodeTemp->val = *(db + i);
nodeTemp->left = BuildTree(da, db, i);
nodeTemp->right = BuildTree(da + i, db + i + 1, n - i - 1);
return nodeTemp;
}
int main(void) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n; i++) {
cin >> b[i];
}
Node* root = (Node*)malloc(sizeof(Node));
root = BuildTree(a, b, n);
queue<Node*> level;
level.push(root);
int flag = 0;
while (true)
{
if (level.front()->left != NULL)
level.push(level.front()->left);
if (level.front()->right != NULL)
level.push(level.front()->right);
cout << level.front()->val;
level.pop();
if (level.empty())
break;
cout << " ";
}
return 0;
}