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.

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def maxDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def maxDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         #return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0
15         return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1  if root else 0

 

posted on 2017-03-15 16:58  Ci_pea  阅读(110)  评论(0编辑  收藏  举报