求二叉树深度 (sdut oj 2804)

本文介绍了一种根据给定的二叉树中序和后序遍历序列求解二叉树深度的方法,并提供了一个完整的C++实现示例。通过递归地构建二叉树并计算其深度,该算法能在限定时间内准确得出结果。

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

求二叉树的深度

Time Limit: 1000MS Memory limit: 65536K

题目描述

已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。

输入

输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。

输出

输出二叉树的深度。

示例输入

2
dbgeafc
dgebfca
lnixu
linux

示例输出

4
3

提示

给出二叉树的中序和后序, 求深度, 和给出前序和中序求高度差不多,只是改一下建立左右子树的顺序就好了 

来源

 

示例程序

#include <bits/stdc++.h>

using namespace std;
struct node
{
    char data;
    node *lchild, *rchild;
}*root;

char str1[75], str2[75];
int Max, k, l;
node *creat()
{
    node *root;
    root = new node;
    root->lchild = NULL;
    root->rchild = NULL;
    return root;
}

node *build(int low, int high)
{
    int flag;
    if(low > high)
        return NULL;
    for(int i = low; i <= high; i++)
    {
        if(str2[k] == str1[i])
        {
            flag = i;
            break;
        }
    }
    k--;
    node *root;
    root = creat();
    root->data = str1[flag];   
    root->rchild = build(flag+1, high);//<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(245, 250, 226);">根节点右侧flag到high为整棵树右子树</span>
    root->lchild = build(low, flag-1);//low到flag为左子树;
    return root;
}

void depth(node *root, int ans)
{
    if(root)
    {
        if(Max < ans)
            Max = ans;
        depth(root->lchild, ans+1);
        depth(root->rchild, ans+1);
    }
}
int main()
{
    int n;
    cin >> n;
    while(n--)
    {
        cin >> str1;
        cin >> str2;
        l = strlen(str1);
        k = l-1;
        root = build(0, l-1);
        Max = 0;
        depth(root, 1);
        cout << Max << endl;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值