题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型
*/
//方法:递归。递归结束条件为:深度为0
//把树分为左右子树,
//然后左子树也可以分为左右子树,
//右子树也可以分为左右子树,
//不断细分下去,然后再不断返回加起来比较
//从简单的思考,拓展到复杂
int TreeDepth(struct TreeNode* pRoot )
{
// write code here
//递归结束条件为:深度为0
if(pRoot == NULL)
{
return 0;
}
//把树分为左右子树,
int leftDep = TreeDepth(pRoot->left); //然后左子树也可以分为左右子树,
int rightDep= TreeDepth(pRoot->right);//右子树也可以分为左右子树,
//三目运算符:满足条件就选择leftDep的值加1,返回
return (leftDep >= rightDep ? leftDep : rightDep) + 1;
}

海康威视公司福利 1282人发布