38、二叉树的深度
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
if(pRoot->left==NULL&&pRoot->right==NULL)
return 1;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return (left>right)?(left+1):(right+1);
}
};总结:
1.递归的写法:
先写出口条件——最基层的思路代码(包含返回值)——递归思路检查正确否
2.大神解法:
class Solution {
public:
int TreeDepth(TreeNode* pRoot){
if(!pRoot) return 0 ;
return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
}
};简洁是简洁,不过加大了理解的难度,把只有一个结点也给归并到一起了,可以。

