leetcode(104). Maximum Depth of Binary Tree

来源:互联网 发布:淘宝lolcdk是真的吗 编辑:程序博客网 时间:2024/06/06 00:37

problem

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.

solution

这个是一个比较经典的递归问题,使用递归的方法是最简单的。

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if root == None:            return 0        elif root.left == None and root.right==None:            return 1        else:            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

这是我第一次提交的代码,后来可以发现可以不用判断左右子树是否是空树,经过优化以后的代码超过了90%的提交。

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if root == None:            return 0        else:            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))