二叉树的建立及遍历
链式
照着算法笔记抄录一份
#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
const int MAX = 30;
struct node{
int data;
node* lchild;
node* rchild;
};
int in[MAX],post[MAX];
int n;
//递归建树
node* creat(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(post[postr]==in[k]) break;
}
int numleft = k-inl;//左子树节点数目
//返回左子树的根节点地址,赋值给root的左指针
root->lchild = creat(postl,postl+numleft-1,inl,k-1);
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* p = q.front();
q.pop();
cout<<p->data;
num++;
if(num<n) cout<<' ';
if(p->lchild!=NULL) q.push(p->lchild);
if(p->rchild!=NULL) q.push(p->rchild);
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++) cin>>post[i];
for(int i=0;i<n;i++) cin>>in[i];
node* root = creat(0,n-1,0,n-1);
BFS(root);
return 0;
}
本文介绍了一种通过后序和中序遍历构建二叉树的方法,并实现了基于队列的广度优先搜索遍历算法。代码示例使用 C++ 编写,展示了如何递归地构建二叉树并进行广度优先遍历。
501

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



