题目 PAT A 1020
题目大意
给出二叉树的中序和后序遍历序列,输出层序遍历序列
解题思路
- 根据中序和后序建立二叉树
- 二叉树的遍历
- 代码中包含了中序,后序,前序,层序遍历的代码
#include<bits/stdc++.h>
using namespace std;
struct Btree{
int data;
Btree *left,*right;
Btree(int d):data(d),left(NULL),right(NULL){}
};
int postorder[31];
int inorder[31];
int cnt=0;
Btree* Build(int postL,int postR,int inL,int inR){
if(postL>postR) return NULL;
Btree* root=new Btree(postorder[postR]);
int index;//在中序序列中查找,该后序元素所在的下标
for(index=inL;index<=inR;++index){
if(inorder[index]==postorder[postR]) break;
}
int leftNum=index-inL;
root->left=Build(postL,postL+leftNum-1,inL,index-1);
root->right=Build(postL+leftNum,postR-1,index+1,inR);
return root;
}
void postOrder(Btree* root){
if(root==NULL) return;
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
void inOrder(Btree* root){
if(root==NULL) return;
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
void preOrder(Btree* root){
if(root==NULL) return;
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
void levelOrder(Btree*root){
queue<Btree *>q;
q.push((root));
while(!q.empty()){
Btree *bt=q.front();
q.pop();
if(cnt==0){
printf("%d",bt->data);
++cnt;
}else printf(" %d",bt->data);
if(bt->left!=NULL) q.push(bt->left);
if(bt->right!=NULL) q.push(bt->right);
}
printf("\n");
}
int main(){
int n;
while(~scanf("%d",&n)){
//给出后序和中序,求层序遍历
for(int i=0;i<n;++i) scanf("%d",&postorder[i]);
for(int i=0;i<n;++i) scanf("%d",&inorder[i]);
Btree *root=Build(0,n-1,0,n-1);
levelOrder(root);
}
return 0;
}
这篇博客介绍了如何根据给定的二叉树中序和后序遍历序列来构建二叉树,并提供了C++代码实现前序、中序、后序和层序遍历。通过递归函数`Build`,实现了从序列到二叉树的构造,然后分别用递归方式完成四种遍历方法的展示。这为理解和操作二叉树提供了一个实用的示例。
488

被折叠的 条评论
为什么被折叠?



