6-9 求二叉树高度(20 point(s))

6-9 求二叉树高度(20 point(s))

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

函数接口定义:

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 ){//如果已知左子树高度和右子树高度
                            //树高为max(Lh,Rh)+1,用后续遍历
    int lh,rh;
    if(BT == NULL)return 0;//实际上是一个导致加的过程,到底时为零
                           //通过递归倒着往回加这样返回出去的时候就是树高
    else{
        lh = GetHeight(BT->Left);
        rh = GetHeight(BT->Right);
        return (lh>rh?lh:rh)+1;
    }
}

 
### C语言实现二叉树高度的方法 在C语言中,可以通过递归的方式计算二叉树高度。以下是具体的实现方法: #### 定义二叉树结构 首先需要定义一个表示二叉树节点的结构体 `tree`,该结构体包含三个成员变量:一个是用于存储数据的数据域 `data`;另外两个是指向左孩子和右孩子的指针 `lchild` 和 `rchild`。 ```c typedef struct node { int data; struct node* lchild; struct node* rchild; } tree; ``` #### 计算二叉树高度函数 为了计算二叉树高度,可以设计如下递归函数 `BTreeHeight` 来完成此任务。如果当前节点为空,则返回高度为 0;否则分别递归计算其左子树和右子树的高度,并取两者中的较大值加一作为最终结果[^4]。 ```c int BTreeHeight(tree* root) { if (root == NULL) { return 0; } int left = BTreeHeight(root->lchild); int right = BTreeHeight(root->rchild); return (left > right) ? (left + 1) : (right + 1); } ``` 上述代码片段展示了如何利用递归来获取一棵给定根节点的二叉树的最大深度即所谓的“高度”。当遇到空节点时停止进一步深入探索并回溯至父级调用处,逐步累积得到整棵树的实际层数信息[^3]。 ### 示例程序 下面给出完整的示例代码,展示如何构建一颗简单的二叉树以及调用上面提到过的函数去测量它的高度: ```c #include <stdio.h> #include <stdlib.h> // Define the structure for a binary tree node. typedef struct node { int data; struct node* lchild; struct node* rchild; } tree; // Function prototypes declaration. tree* createTreeNode(int value); void destroyTree(tree* t); int calculateBinaryTreeHeight(tree* root); // Main function demonstrating usage of our functions. int main() { // Create sample nodes forming part of a small binary search tree. tree* root = createTreeNode(1); root->lchild = createTreeNode(2); root->rchild = createTreeNode(3); root->lchild->lchild = createTreeNode(4); root->lchild->rchild = createTreeNode(5); printf("The height of this binary tree is %d.\n", calculateBinaryTreeHeight(root)); // Clean up memory before exiting program execution flow completely. destroyTree(root); return EXIT_SUCCESS; } /** * Helper method used internally within other methods but exposed here so it can be reused elsewhere too as needed later on potentially depending upon use case requirements etc... */ tree* createTreeNode(int value){ tree* newNode=(tree*)malloc(sizeof(struct node)); newNode->data=value; newNode->lchild=NULL; newNode->rchild=NULL; return(newNode); } /** * Recursive helper routine responsible primarily towards freeing all dynamically allocated resources associated with each individual element present inside given input parameter &#39;t&#39;. */ void destroyTree(tree* t){ if(t!=NULL){ destroyTree(t->lchild); destroyTree(t->rchild); free(t); } } /** Calculates and returns the maximum depth/height from current position downwards recursively until reaching leaf level where no more children exist anymore.*/ int calculateBinaryTreeHeight(tree* root){ if(!root){return 0;} int leftSubtreeDepth=calculateBinaryTreeHeight(root->lchild); int rightSubtreeDepth=calculateBinaryTreeHeight(root->rchild); return ((leftSubtreeDepth>rightSubtreeDepth)?leftSubtreeDepth:rightSubtreeDepth)+1; } ``` 问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值