2804 数据结构实验之二叉树八:(中序后序)求二叉树的深度

本文介绍了一种使用中序和后序遍历序列构建二叉树的方法,并通过递归方式实现计算该二叉树的深度。通过输入中序和后序遍历序列,程序能够构建出相应的二叉树结构,并最终输出树的深度。

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

数据结构实验之二叉树八:(中序后序)求二叉树的深度

#include<iostream>
#include <malloc.h>
#include<string.h>
using namespace std;
struct node
{
    char data;
    struct node  *rchild,*lchild;
}tree;
struct node *creat(char *a1,char*a2,int n)
{
    struct node *root;
    if(n<=0) return NULL;
    else
    {
        root=(struct node *)malloc(sizeof(struct node ));
        root->data=a2[n-1];
        //将后序遍历的最后一个节点当作当前子树的根
        /*        指针形式
        char *a;
        for (a=a1;a!=NULL;a++)
    {
            if(*a==a2[n-1])
                break;
        }
        int lchildroot=a-a1;//左子树的长度
        root->lchild=creat(a1,a2,lchildroot);
        root->rchild=creat(a1+1+lchildroot,a2+lchildroot,n-lchildroot-1);
        */
        int i;                   //数组形式
        for ( i=0;i<n;i++)
        {
            if(a1[i]==a2[n-1])
                break;
        }
        int lchildroot=i;//左子树的长度
        root->lchild=creat(a1,a2,lchildroot);
        root->rchild=creat(a1+1+lchildroot,a2+lchildroot,n-lchildroot-1);
    }
  return root;
};
int deep(struct node *root)
{
    int d=0;
    if(root)
    {
        int l=deep(root->lchild);
        int r=deep(root->rchild);
        d=l>r?l+1:r+1;
    }
    return d;
}
int main()
{
    int n,x;
    cin>>x;
    while(x--)
    {

        char a1[55],a2[55];
        struct node *root;
        cin>>a1>>a2;
        n=strlen(a1);
        root=creat(a1,a2,n);
        cout<<deep(root)<<endl;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值