题目描述:
题解:
采用DFS方法:
DFS对二叉树从根节点开始搜索,根结点位置depth为1
列表depthlist保存叶子结点对应的depth
然后depth+1在root的左右子节点分别调用DFS函数
class Solution(object): def minDepth(self, root): if root is None: return 0 depth = 1 depthlist = [] depthlist = self.DFS(root,depth,depthlist) mindepth = min(depthlist) return mindepth def DFS(self,root,depth,depthlist): if root==None: return 0 if root.left==None and root.right==None: depthlist.append(depth) self.DFS(root.left,depth+1,depthlist) self.DFS(root.right,depth+1,depthlist) return depthlist
LeetCode-111- 二叉树的最小深度(python) - 简书提供了一种更简单的解法。
class Solution(object): def minDepth(self,root): if root==None: return 0 if root.left==None and root.right==None: return 1 if root.left==None: return self.minDepth(root.right)+1 if root.right==None: return self.minDepth(root.left)+1 return min(self.minDepth(root.left),self.minDepth(root.right))+1
二叉树的最小深度有以下几种情况:
1.root为空,最小深度为0
2.root不为空,但root左右子树为空,最小深度为1
3.root左子树为空,最小深度为右子树最小深度+1
4.root右子树为空,最小深度为左子树最小深度+1
5.左右子树都存在,最小深度=min(左子树最小深度,右子树最小深度)+1
注意:对左右子树是否为空的判断不能缺少,比如题目中示例2的情况,二叉树为:
此时左子树为空,会返回0的最小深度,如果直接使用min(self.minDepth(root.left),self.minDepth(root.right))+1求解,会得到最小深度为1的错误答案。