题解 | #二叉树的深度#

二叉树的深度

https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

解题思路

  • 如果当前节点值为空,则返回0;
  • 否则递归实现,每遍历一层增加层数1,并遍历左子树和右子树,选择大的一方。

复杂度

  • 时间复杂度为O(N);
  • 空间复杂度为O(N)。

代码

Python

class Solution:
    def TreeDepth(self , pRoot: TreeNode) -> int:
        if not pRoot:
            return 0

        return 1+max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right))

C++

class Solution {
public:
    int TreeDepth(TreeNode* pRoot) {
		if(pRoot == NULL)
		{
			return 0;
		}

		return 1+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
    }
};
全部评论

相关推荐

03-15 12:48
门头沟学院 Java
牛牛要早起:这个一般就跟你说有高薪,然后叫你买车,之后血亏
点赞 评论 收藏
分享
劝退式:感觉有人回才是不正常的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务