[LeetCode] 104. Maximum Depth of Binary Tree_Easy tag: DFS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 104. Maximum Depth of Binary Tree_Easy tag: DFS相关的知识,希望对你有一定的参考价值。

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

以上是关于[LeetCode] 104. Maximum Depth of Binary Tree_Easy tag: DFS的主要内容,如果未能解决你的问题,请参考以下文章