参考资料:
[1]Gaowh的回答:
https://www.nowcoder.com/profile/642820/codeBookDetail?submissionId=16839628
自己的解答:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
//终止条件
if(pRoot ==nullptr)
return 0;
//统计左子树的深度
int leftdepth = TreeDepth(pRoot->left);
//统计右子树的深度
int rightdepth = TreeDepth(pRoot->right);
//取左子树和右子树的深度最大的再+1为树的深度
int depth = 1+max(leftdepth,rightdepth);
return depth;
}
};
标准答案
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
return max(1+TreeDepth(pRoot->left),1+TreeDepth(pRoot->right));
}
};