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
解题思路
通过给出的中序和后序遍历输出二叉树的层序遍历结果。解题步骤如下:
-
通过给出的中序和后序建立二叉树。
建立二叉树是关键, 通过递归的方式建立二叉树, 如图
后序中找到根节点,一定是后序中最后一个数作为根节点,通过找到的根节点在中序遍历中枚举找到根结点,找到后根左侧为左子树, 右侧为右子树, 此时左子树的结点个数为 num = k - inL, 在后序遍历中左子树的范围就是[postL, postL + num - 1 ], 右子树的范围就是[postL + num , postR - 1], 在中序遍历中左子树范围就是[inL, ink - 1], 右子树的范围[in k + 1, inR], 在第一次找到了范围后,递归进行依次找到左右子树作为下一层的根节点, 直到先序长度小于零结束。
-
bfs层序遍历二叉树,输出结点信息。
解题代码
#include <cstdio>
#include <queue>
using namespace std;
const int N = 50;
int n;
struct node{
int data;
node* lchild;
node* rchild;
};
int in[N], post[N];
node *create(int postL, int postR, int inL, int inR){
if (postL > postR) return NULL;
node* root = new node;
root->data = post[postR];
int k;
for (k = inL; k <= inR; k++)
if (in[k] == post[postR])
break;
int numLeft = k - inL;
root->lchild = create(postL, postL + numLeft - 1, inL, k - 1);
root->rchild = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num;
void bfs(node* root){
queue<node*> q;
q.push(root);
while (!q.empty()){
node* cur = q.front();
q.pop();
printf("%d", cur->data);
num++;
if (num < n) printf(" ");
if (cur->lchild != NULL) q.push(cur->lchild);
if (cur->rchild != NULL) q.push(cur->rchild);
}
}
int main(){
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &post[i]);
for (int i = 0; i < n; i++) scanf("%d", &in[i]);
node* root = create(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}