【LeetCode每天一题】 Minimum Depth of Binary Tree(二叉树的最小深度)

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest 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 minimum depth = 2.

 

思路


  之前做过二叉树的最大深度,直接使用递归解决。这道题让计算出最小的深度,其中在写代码的时候发现一个问题就是如果根节点的左子树或者右子树不存在时,选择存在的子树中的最小深度加1(1代表的根节点)作为最小深度。对于这个特殊的情况,我们可以在求最大深度的代码上稍微改变一下。求出结果。其中给出了两种解决办法一种是直接使用递归,另一种是使用辅助空间栈来解决。

解决代码 


 

 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 minDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         if not root:      # 为空直接返回0
15             return 0
16         left = self.minDepth(root.left)   # 左子树的高度
17         right = self.minDepth(root.right)   # 右子树的高度
18         if left == 0 or right == 0:        # 这就是如果根节点的左子树或者右子树其中一个为空时,返回不为空的子树的最低高度
19             return left + right +1         # left+right+1 因为其中一个为0
20         return min(left, right) +1         # 否则返回左右子树中最小的值

   使用辅助空间栈进行解决(这里的写法和之前层次遍历的时候写法完全一致,只不过这里多了一个条件判断)

 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 minDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """        
14         if not root:
15             return 0
16         stack = [root]    # 辅助空间栈来来存储。
17         depth = 0        # 当前深度变量
18         while stack:
19             depth += 1
20             count = len(stack)   # count表示当前层的节点个数
21             for _ in range(count):     #   遍历几次
22                 tem = stack.pop(0)      
23                 if tem.left:            # 将左右节点不为空时添加进来。
24                     stack.append(tem.left)
25                 if tem.right:
26                     stack.append(tem.right)
27                 if not tem.left and not tem.right:   # 如果当前节点的左右节点都为空时,直接返回结果。该结果就是最小深度
28                     return depth   

 

转载于:https://www.cnblogs.com/GoodRnne/p/10871740.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值