题意:
根据一棵二叉树的后序遍历和中序遍历来输出层序遍历结果。
分析:
首先想到的是,先根据后序和中序遍历结果来构造一颗二叉树。如何构造?一棵二叉树(子树也一样)的后序遍历的最后一个节点就是整棵树(子树)的根节点,然后可以利用这一个根节点到中序遍历中去查找,然后左边的即为左子树,右边的即为右子树。生成二叉树完了过后就简单了,利用队列的原理然后进行层序遍历。
代码:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node
{
int value;
node*left;
node*right;
};
int N;
vector<int>postorder;
vector<int>inorder;
void handleInput()
{
cin>>N;
int temp;
for(int i=0;i<N;++i)
{
cin>>temp;
postorder.push_back(temp);
}
for(int i=0;i<N;++i)
{
cin>>temp;
inorder.push_back(temp);
}
}
//重构二叉树
//参数分别是该子问题在后序遍历和中序遍历序列中的范围
node * rebuildBinaryTree(int postL, int postR, int inL, int inR)
{
if(postL>postR)
{
return NULL;
}
node *root=new node;
root->value=postorder[postR];
int k=inL-1;
while(inorder[++k]!=postorder[postR]);
int numLeft=k-inL;
//递归解决左子树的子问题
root->left=rebuildBinaryTree(postL,postL+numLeft-1,inL,k-1);
//递归解决右子树的子问题
root->right=rebuildBinaryTree(postL+numLeft,postR-1,k+1,inR);
return root;
}
// 层序遍历
void BFS(node *root)
{
queue<node*>q;
q.push(root);
int i=0;
while(q.size()!=0)
{
node* visit=q.front();
q.pop();
cout<<visit->value;
++i;
if(i<N)
cout<<" ";
if(visit->left!=NULL)
q.push(visit->left);
if(visit->right!=NULL)
q.push(visit->right);
}
}
int main()
{
handleInput();
node *root=rebuildBinaryTree(0,N-1,0,N-1);
BFS(root);
return 0;
}