链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
从题意可以看出,最小深度是指从根节点到最近叶子节点的最短路径上的节点数量。所以,我们需要对整棵树进行遍历,找到所有路径中节点最少的一条路径。遍历可以通过深度优先遍历和广度优先遍历,深度优先遍历需要把所有的路径都遍历完,然后找所有路径中节点数量最少的那条路径。而广度优先遍历是一层一层遍历,只要我们在遍历的时候当前层一旦有叶子节点,这个叶子节点所在的路径即是最小深度的那条路径,此时返回节点数量即可。
当我们使用递归的时候,很重要的就是递归的结束条件,如果不能结束递归,很容易让代码陷入死循环,无法走出来。
时间复杂度:O(n)
空间复杂度:O(n)
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
l=self.minDepth(root.left)
r=self.minDepth(root.right)
if not root.left or not root.right:
return l+r+1
return min(l,r)+1
时间复杂度:O(n)
空间复杂度:O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
queue=deque()
queue.append((root,1))
while queue:
node,depth=queue.popleft()
if not node.left and not node.right:
return depth
if node.left:
queue.append((node.left,depth+1))
if node.right:
queue.append((node.right,depth+1))
from collections import deque
def minDepth(root):
if not root:
return 0
queue=deque([root])
depth=1
while queue:
size=len(queue)
for i in range(size):
node=queue.pop()
if not node.left and not node.right:
return depth
if node.left:
queue.appendleft(cur.left)
if node.right:
queue.appendleft(cur.right)
depth+=1
return depth
如果觉得文章不错,希望大家可以关注我噢,点赞、收藏、在看、分享就再好不过了。如果有任何建议和问题,可以在下方给我留言,我会不定期更新更多的文章,祝我们终将自由。