在二叉树中,深度是指从根节点到最远叶子节点的最长路径上的边数。求解二叉树的深度通常采用递归的方法,以下便是求二叉树深度的C代码实现:
#include <stdio.h>
// 假设已经定义了二叉树节点结构体
typedef struct BiTreeNode {
int data; // 节点数据(这里假设为整型)
struct BiTreeNode *left, *right; // 左、右子节点指针
} BiTree;
// 函数声明
int Depth(BiTree *T);
// 计算二叉树的深度函数
int Depth(BiTree *T) {
if (T == NULL) { // 空树的深度为0
return 0;
} else {
// 计算左子树和右子树的深度
int left_depth = Depth(T->left);
int right_depth = Depth(T->right);
// 返回左右子树中的较大深度 + 1(加1是因为包括当前节点)
return (left_depth > right_depth) ? (left_depth + 1) : (right_depth + 1);
}
}
// 示例:创建并初始化一个二叉树,并调用Depth函数计算其深度
int main() {
// 创建二叉树的过程在此省略,假设已经有了一个根节点指针root
BiTree *root = ...; // 初始化或通过某种方式得到根节点
// 计算二叉树的深度
int tree_depth = Depth(root);
printf("The depth of the binary tree is