[LeetCode] 104. Maximum Depth of Binary Tree_Easy tag: DFS
2018-07-09 23:31 Johnson_强生仔仔 阅读(180) 评论(0) 编辑 收藏 举报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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
思路就是DFS, 然后返回children 的depth的最大值 + 1, 依次循环, base case就是None, return 0.
1. Constraints
1) root : empty => 0
2. Ideas
DFS T: O(n) S; O(n) # need to save all the temprary depth for each children
3. Code
1 class Solution: 2 def maxDepth(self, root): 3 if not root: return 0 4 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
4. Test cases
1) None => 0
2) 2 => 1
3)
3 / \ 9 20 / \ 15 7