PTA数据结构 6-1求二叉树高度

PTA数据结构 6-1求二叉树高度

题目概述

本题要求给定二叉树的高度。## 参考代码

函数接口定义

int GetHeight( BinTree BT );

其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

要求函数返回给定二叉树BT的高度值。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
int GetHeight( BinTree BT );

int main()
{
    BinTree BT = CreatBinTree();
    printf("%d\n", GetHeight(BT));
    return 0;
}
/* 你的代码将被嵌在这里 */

输出样例

在这里插入图片描述

4

参考代码

//利用高度的递归定义
int GetHeight( BinTree BT )   //返回值为当前树的高度
{
    int L,R;      //初始化二叉树左右两个分支的高度
    if(BT==NULL)  //判断是否空树,同时也是递归调用的终止条件
    {
        return 0;
    }
	else
	{
		L=GetHeight(BT->Left);    //左子树的高度
		R=GetHeight(BT->Right);   //右子树的高度
        if(L>=R)                  //返回高度高的子树+1
        {
            return L+1;
        }
		else
        {
            return R+1;
        }

	}
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值