二叉树的高度
思路
- 分别计算左子树和右子树的高度
- 二叉树的最终高度为两个子树高度的最大值
- 递归实现
代码实现
//二叉树结点
typedef struct BINARYNODE{
char ch;
struct BINARYNODE* lchild;
struct BINARYNODE* rchild;
}BinaryNode;
//求二叉树的高度
int CaculateTreeDepth(BinaryNode* root){
if(root==NULL)
{
return 0;
}
int depth=0;
//求左子数的高度
int leftDepth=CaculateTreeDepth(root->lchild);
//求右子树的最大高度
int rightDepth = CaculateTreeDepth(root->rchild);
//将depth置为两个子树的最大值
depth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
return depth;
}