由前序或后序和中序建立二叉树

这篇博客主要介绍了如何根据前序和中序序列,以及中序和后序序列来重建二叉树。内容包括解析这两种情况的算法思路,并提供了相应的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文章:点一下

1.通过前序序列和中序序列建立二叉树

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
    char data;
    struct node *left;
    struct node *right;
}Tree;
string a;
string b;
//根据前序和中序建立二叉树
Tree *bulid(int l1,int l2,int r1,int r2)
{
    if(l1>l2)
    {
        return NULL;
    }
    Tree *root=new Tree();
    root->data=a[l1];
    int p=0;
    while(root->data!=b[p])
    {
        p++;
    }
    int llem=p-r1;
    root->left=bulid(l1+1,l1+llem,r1,r1+p-1);
    root->right=bulid(l1+llem+1,l2,p+1,r2);
}
void xian(Tree *root)
{
    if(root!=NULL)
    {
        xian(root->left);
        xian(root->right); 
        printf("%c",root->data);  
    }
}
int main()
{
    Tree *root;
    root=NULL;
    cin>>a;
    cin>>b;
    int m,n;
    m=a.size();
    n=b.size();
    root=bulid(0,m-1,0,n-1);
    xian(root);
}

通过中序序列和后序序列建立树

下面代码是将前序序列输出出来的

#include<bits/stdc++.h>
using namespace std;
char pre[40];
char in[40];
int len;
typedef struct BiNode{
     char data;
     struct BiNode *lchild;
     struct BiNode *rchild;
}Tree;

//根据中序序列和后序序列建树
Tree *bulid2(int l1,int r1,int l2,int r2)
{
    //cout<<l1<<' '<<r1<<' '<<l2<<' '<<r2<<endl;
    if(r2<l2)
    {
        //cout<<"NULL"<<endl;
         return NULL;
    }
   
    
    Tree *root=new Tree();
    root->data=in[r2];
   // cout<<in[r2]<<endl;
    int p=0;
    while(pre[p]!=root->data)
    {
        p++;
    }
    
    int llen=p-l1;
    root->lchild=bulid2(l1,p-1,l2,l2+p-l1-1);
    root->rchild=bulid2(p+1,r1,l2+p-l1,r2-1);
    return root;
  /* 测试数据
DCBAEFG
DCBGFEA

    */
}
void postOrder(Tree* root){
    if(root!=NULL){
        cout<<root->data;
        postOrder(root->lchild);
        postOrder(root->rchild);
        
    }
} 
int main()
{
    while(gets(pre)!=NULL){
         len=strlen(pre);
         gets(in);
        Tree *root=bulid2(0,len-1,0,len-1);
         postOrder(root);
        cout<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值