104. Maximum Depth of Binary Tree

求一棵二叉树的最大深度

思路:递归

1
2
3
4
5
6
7
8
9
10
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# 5 star
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

Go:

1
2
3
4
5
6
7
8
9
10
func maxDepth(root *TreeNode) int {
if root == nil {return 0}
return max(maxDepth(root.Left), maxDepth(root.Right)) + 1

}

func max(a, b int) int {
if a > b {return a}
return b
}