郑州轻工业大学2020年数据结构练习集-6-9 求二叉树高度 (20分)

本题要求给定二叉树的高度。

函数接口定义:

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 ){
    //left
    int left_height = 0, right_height = 0;
    if(BT->Left != NULL)
        left_height = 1 + GetHeight(BT->Left);
    else
        left_height = 1;
    //right
    if(BT->Right != NULL)
        right_height = 1 + GetHeight(BT->Right);
    else
        right_height = 1;
    if(left_height > right_height)
        return left_height;
    else return right_height;
}

稍微优化一下

int GetHeight( BinTree BT ){
    if(BT == NULL)
        return 0;
    //left
    int left_height = 0, right_height = 0;
    left_height = 1 + GetHeight(BT->Left);
    //right
    right_height = 1 + GetHeight(BT->Right);
    if(left_height > right_height)
        return left_height;
    else return right_height;
}
原创文章 93 获赞 353 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43906799/article/details/105203365