Leetcode:111. 二叉树的最小深度 - 力扣(LeetCode) (leetcode-cn.com)
求解根节点到最近叶子节点的最短路径,可以用BFS也可以用DFS。
是求最短路径问题的二叉树简化版本。
BFS:
时间复杂度:O(n)
空间复杂度:O(n)
代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
queue,visited=[],[]
if root:
queue.append(root)
depth=1
else:
depth=0
while queue:
tmp=[]
while queue:
node=queue.pop(0)
if node.left is None and node.right is None:
return depth
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
depth+=1
queue=tmp
return depth