下面是一个计算二叉树深度的递归函数实现:
int Depth(BiTNode *T) {
if (T == nullptr) { // 空树,深度为0
return 0;
} else {
int left_depth = Depth(T->lchild); // 递归计算左子树深度
int right_depth = Depth(T->rchild); // 递归计算右子树深度
return (left_depth > right_depth ? left_depth : right_depth) + 1; // 取左右子树深度较大者加1作为当前层的深度
}
}
使用上述函数可以计算并返回二叉树的深度。
内容由零声教学AI助手提供,问题来源于学员提问