首页 > 其他 > 详细

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

时间:2018-07-10 00:11:02      阅读:298      评论:0      收藏: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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!