单词积累
postorder 后序
inorder 中序
level order 层次
题目
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
结尾无空行
思路
根据中序遍历和后续遍历建树,然后对树进行层次遍历。
关键在于递归进去的边界值。
代码
#include <bits/stdc++.h>
using namespace std;
int len;
const int maxn = 1000;
int post[maxn];
int in[maxn];
struct node {
int data;
node* leftchild;
node* rightchild;
node(int d): data(d), leftchild(NULL), rightchild(NULL) {
}
};
node* create(int a, int b, int c, int d) {
if (a > b) {
return NULL;
}
int ro = post[b];
// cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<ro<<endl;
node* root = new node(ro);
int i;
for (i = c; i <= d; i++) {
if (in[i] == ro) break;
}
int numleft = i - c;
root->leftchild = create(a, a + numleft - 1, c, i - 1);
root->rightchild = create(a + numleft, b - 1, i + 1, d);
return root;
}
void level(node *root) {
queue<node*> tra;
tra.push(root);
int flag = 0;
while (!tra.empty()) {
node* now = tra.front();
tra.pop();
if (flag == 0) {
cout<<now->data;
flag = 1;
} else {
cout<<" "<<now->data;
}
if(now->leftchild != NULL) tra.push(now->leftchild);
if(now->rightchild != NULL) tra.push(now->rightchild);
}
}
int main() {
cin>>len;
for (int i = 0; i < len; i++) {
cin>>post[i];
}
for (int i = 0; i < len; i++) {
cin>>in[i];
}
node* root = create(0, len - 1, 0, len - 1);
level(root);
}