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
题意:
给出一棵树的结点数和中序遍历以及后序遍历,求其层次遍历。
思路:
在后序序列中,根结点是最后一个。在中序序列中找到它就可以将左右子树区分开。然后就可以重建二叉树,再使用广度优先遍历(BFS)进行层次遍历。
分析:
左子树的结点个数numLeft = k - inL
左子树中序序列[inL, k - 1],后序序列 [postL, postL + numLeft - 1]。
右子树中序序列[k + 1, inR],后序序列 [postL + numLeft, postR - 1]。
后记:类似还有已知道中序序列和先序序列,思路很相似。
仍然是左子树的结点个数numLeft = k - inL
左子树中序序列[inL, k - 1],先序序列 [preL + 1, preL + numLeft]。
右子树中序序列[k + 1, inR],先序序列 [preL + numLeft + 1, preR]。
还有一点不同的就是后序遍历,后序遍历代码如下。
int num = 0;
void postOrder(node* root) //后序遍历
{
if(root == NULL) return;
postOrder(root->lchild); //左
postOrder(root->rchild); //右
printf("%d", root->data); //根
num++;
if(num < n) //控制输出格式(最后一个数后面不能有空格)
printf(" ");
}
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 50;
struct node
{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], in[maxn], post[maxn]; //前序中序后序序列
int n; //结点个数
//当前二叉树的后序序列为[postL,postR],中序序列为[inL,inR]
node* creat(int postL, int postR, int inL, int inR) //返回构建出的二叉树的根结点地址
{
// if(postL > postR) //两个if语句都可以
// return NULL;
if(inL > inR) //序列长度小于等于0,直接返回
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的左值针
root->lchild = creat(postL, postL + numLeft - 1, inL, k - 1);
返回右子树的根结点地址,赋值给root的右值针
root->rchild = creat(postL + numLeft, postR - 1, k + 1, inR);
return root; //返回根结点地址
}
int num = 0; //记录已输出结点的个数
void BFS(node* root)
{
queue<node*> q; //注意队列里存的是地址
q.push(root); //根结点地址入队
while(!q.empty())
{
node* now = q.front(); //取队首元素
q.pop();
printf("%d", now->data); //访问队首元素
num++;
if(num < n) printf(" "); //控制输出格式
if(now->lchild != NULL) //左子树非空
q.push(now->lchild);
if(now->rchild != NULL) //右子树非空
q.push(now->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 = creat(0, n - 1, 0, n - 1); //建树
BFS(root); //层次遍历
return 0;
}