SDUT 2804 求二叉树的深度

本文介绍了一种使用后缀和中缀表达式来构建二叉树的方法,并提供了一个完整的C++实现示例。该方法通过遍历后缀表达式,结合中缀表达式确定每个节点的位置,从而构建出对应的二叉树结构。

点击打开题目链接

与前缀中缀建树类似,只不过前缀中缀首先建立左子树,后缀中缀首先建立右子树

#include <bits/stdc++.h>
using namespace std;

struct node
{
    char data;
    node *right, *left;
};

int len, k;
char str1[60], str2[60], str3[60];
node *creat();
int high(node *root);//二叉树高度
node *build(int low, int high);//还原二叉树

int main()
{
    int n;
    while(cin >> n)
    {
        while(n --)
        {
            scanf("%s", str1);
            scanf("%s", str2);
            len = strlen(str1);
            k = len-1;
            node *root = build(0,len-1);
            cout << high(root) << endl;
        }
    }
    return 0;
}

node *creat()
{
    node *root = new node;
    root -> left = NULL;
    root -> right = NULL;
    return root;
}

int high(node *root)
{
    int highleft, highright;
    if(root)
    {
        highleft = high(root -> left);
        highright = high(root -> right);
        return max(highleft, highright)+1;
    }
    else return 0;
}

node *build(int low, int high)
{
    int flag;
    if(low > high || k < 0)//***DuangDuangDuang
        return NULL;
    for(int i = low; i <=  high; i++)
    {
        if(str2[k] == str1[i])
        {
            flag = i;
            break;
        }
    }
    k--;
    node *root = creat();
    root -> data = str1[flag];
    root -> right = build(flag+1,high);//根节点左侧flag到high为整棵树右子树////**
    root -> left = build(low, flag-1);//low到flag为整棵树的左子树////**
    return root;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值