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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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   

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄