求二叉树高度

因为树是递归定义的,所以用递归算法很方便。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
using namespace std;

struct Node {
	char data;
	Node *lchild;
	Node *rchild;
};

void High(Node *T, int &h)
{
	if (T == NULL)
		h = 0;
	else {
		int left_h;
		High(T->lchild, left_h);
		int right_h;
		High(T->rchild, right_h);

		h = 1 + max(left_h, right_h);
	}
}

Node *CreateBiTree(Node *&T) {  // 算法6.4
	// 按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树,
	// 构造二叉链表表示的二叉树T。
	char ch;
	cin >> ch;
	if (ch == '#')
		T = NULL;
	else {
		if (!(T = (Node *)malloc(sizeof(Node))))
			return 0;
		T->data = ch;              // 生成根结点
		CreateBiTree(T->lchild);   // 构造左子树
		CreateBiTree(T->rchild);   // 构造右子树
	}
	return T;
} // CreateBiTree

void Free(Node *&T)
{
	if (T == NULL)
		return;

	Free(T->lchild);
	//	T->lchild = NULL;
	Free(T->rchild);
	//	T->rchild = NULL;
	free(T);
	T = NULL;
}

int main(int argc, char **argv)
{
	freopen("cin.txt", "r", stdin);

	Node *T = NULL;
	CreateBiTree(T);

	int height;
	High(T, height);
	cout << height << endl;

	Free(T);

	return 0;
}

/* cin.txt:
A
B
C
#
#
D
E
#
G
#
#
F
#
#
#
*/

构造的树:

输出为5。

### 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 't'. */ 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、付费专栏及课程。

余额充值