题目描述
解题
DFS
DFS使用分治法,每次寻找左右两子书的最小高度,区分以下几种终止条件:
- 当前结点为空,返回0
- 当前结点左右子树有一为空,返回左子树最小高度与右子树最小高度和并+1(有一为0)
- 当前结点左右子树都为空,返回左右子树最小高度中较小的值并+1
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
min_l = self.minDepth(root.left)
min_r = self.minDepth(root.right)
if not root.left or not root.right:
return min_l+min_r+1
return min(min_l,min_r)+1
BFS
BFS比较简单易于理解,可以参考最大高度104
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
que = deque([root])
height = 0
while que:
num = len(que)
while num>0:
node = que.popleft()
if not node.left and not node.right:
return height+1
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
num -= 1
height = height+1