104. 二叉树的最大深度

Problem

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],
104. 二叉树的最大深度
返回它的最大深度 3 。

too young 思路

思路是递归,一直找到left 和 right都是None为止,返回长度,但是代码怎么写都不对

dalao 思路-32ms

36ms的答案

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxDepth(self, root):
        if root:
            return 1 + max(map(self.maxDepth, (root.left, root.right)))
        else:
            return 0      

一点trick,32ms

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxDepth(self, root):
        if root:
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
        else:
            return 0