题解 | #二叉树的深度#

二叉树的深度

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() 函数。

全部评论

相关推荐

10-26 13:03
已编辑
门头沟学院 物流经理
在okr拆解的小太阳...:实习待过,我待的部门氛围很好,基本不加班,双休有保证。
投递正浩创新EcoFlow等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务