111. Minimum Depth of Binary Tree 二叉树的最短路径
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.
题意:给一个二叉树,求出根节点到叶子节点(终端结点)的最短路径
解法:使用BFS广度优先遍历,记录层数,遇到左右同时为null,返回层数
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if(not root):
return 0
queue = [root]
level = 1
while(queue):
count = len(queue)
for i in range(0, count):
node = queue.pop(0)
if(not node.left and not node.right):
return level
if(node.left):
queue.append(node.left)
if(node.right):
queue.append(node.right)
level += 1
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步