返回
代码实现--递归下探二叉树的最小深度
前端
2024-02-14 04:38:56
大家好,今天跟大家分享一道LeetCode的中等难度题目:[111. 二叉树的最小深度]
题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
提示:
- 树中节点数的范围在 [0, 105] 内。
- -1000 <= Node.val <= 1000
递归实现
时间复杂度: O(n),其中 n 为二叉树的节点数。
空间复杂度: O(n),在最坏情况下,空间复杂度为 O(n)。因为在最坏情况下,递归调用栈的深度可能达到 n。
def min_depth(root):
if not root:
return 0
if not root.left and not root.right:
return 1
min_left = min_depth(root.left)
min_right = min_depth(root.right)
if not root.left:
return min_right + 1
if not root.right:
return min_left + 1
return min(min_left, min_right) + 1
Python代码实现
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_depth(root):
if not root:
return 0
if not root.left and not root.right:
return 1
min_left = min_depth(root.left)
min_right = min_depth(root.right)
if not root.left:
return min_right + 1
if not root.right:
return min_left + 1
return min(min_left, min_right) + 1
if __name__ == "__main__":
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
min_depth_result = min_depth(root)
print(min_depth_result) # 输出:2
总结
在本文中,我们学习了如何使用递归算法来求解二叉树的最小深度。我们提供了详细的算法、图解和复杂性分析,并提供了 Python 代码实现。希望这篇文章对您有所帮助。