题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
解题思路:二叉树的深度 = 根节点左子树的深度与根节点右子树的深度中的较大值 + 1
int TreeDepth(TreeNode* pRoot)
{
if (NULL == pRoot){
return 0;
}
if (NULL == pRoot->left && NULL == pRoot->right){
return 1;
}
int leftDepth = 0;
int rightDepth = 0;
leftDepth = TreeDepth(pRoot->left);//求左子树的深度
rightDepth = TreeDepth(pRoot->right);//求右子树的深度
int deepth = 0;
deepth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
return deepth;
}
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
解题思路:二叉树的深度 = 根节点左子树的深度与根节点右子树的深度中的较大值 + 1
int TreeDepth(TreeNode* pRoot)
{
if (NULL == pRoot){
return 0;
}
if (NULL == pRoot->left && NULL == pRoot->right){
return 1;
}
int leftDepth = 0;
int rightDepth = 0;
leftDepth = TreeDepth(pRoot->left);//求左子树的深度
rightDepth = TreeDepth(pRoot->right);//求右子树的深度
int deepth = 0;
deepth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
return deepth;
}
本文介绍了一种递归算法来计算二叉树的深度。通过比较左右子树的深度并加一来确定整棵树的最大深度。
334

被折叠的 条评论
为什么被折叠?



