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

23-104. Maximum Depth of Binary Tree

时间:2019-06-14 00:46:20      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:dep   ber   maximum   val   The   nod   init   ret   code   

题目描述:

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.

代码实现:

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def maxDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         if not root:
15             return 0
16 
17         return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

 

分析:

用递归的方法,分别深入左子树和右子树中去找,当左、右子树不存在时,抵达递归基,此时return 0.

23-104. Maximum Depth of Binary Tree

标签:dep   ber   maximum   val   The   nod   init   ret   code   

原文地址:https://www.cnblogs.com/tbgatgb/p/11020548.html

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