码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-10 00:37:31      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:with   des   binary   children   The   nbsp   int   str   nts   

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

标签:with   des   binary   children   The   nbsp   int   str   nts   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9286719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!