题解 | #二叉树的深度#
二叉树的深度
http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
/*
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){
int left_d = 1, right_d = 1;
if(pRoot->left != nullptr){
left_d += TreeDepth(pRoot->left);
}
if(pRoot->right != nullptr){
right_d += TreeDepth(pRoot->right);
}
return max(left_d, right_d);
} else{
return 0;
}
}
};
这道题用递归就可以很方便地解决,只需要一个函数,甚至都不需要 help() 函数。