https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
思路1:dfs递归
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
#递归出口,空节点
if not root:
return 0
min_depth = sys.maxsize
#dfs
min_depth = min(self.minDepth(root.left), min_depth)
min_depth = min(self.minDepth(root.right), min_depth)
return min_depth + 1
误区:对[1,2]这组数据,输出是1,但是正确为2,因为右子为空,不构成叶子。
需要对叶节点额外考虑
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
#递归出口,没有左右子,叶节点
if not root.left and not root.right:
return 1
min_depth = sys.maxsize #最小深度假设为最大整数
#若左子存在,对其dfs递归
if root.left:
min_depth = min(self.minDepth(root.left), min_depth)
#若右子存在,对其dfs递归
if root.right:
min_depth = min(self.minDepth(root.right), min_depth)
return min_depth + 1
思路2:层序。从根开始计算深度,初始=1。遇到叶节点就查看当前深度,并与最小深度记录比较。
import queue
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
depth = 0
min_depth = sys.maxsize #记录最小深度
q = queue.Queue()
q.put(root)
#层序
while not q.empty():
depth += 1
count = q.qsize()
for _ in range(count):
tmp = q.get()
if tmp.left:
q.put(tmp.left)
if tmp.right:
q.put(tmp.right)
if not tmp.left and not tmp.right:
min_depth = min(depth, min_depth)
return min_depth