參考資料:
[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;
//統(tǒng)計左子樹的深度
int leftdepth = TreeDepth(pRoot->left);
//統(tǒng)計右子樹的深度
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));
}
};