diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 430cd5d6..6c6b4632 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -195,9 +195,51 @@ public: Java: - Python: +递归法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left and not root.right: + return 1 + + min_depth = 10**9 + if root.left: + min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 + if root.right: + min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 + return min_depth + 1 +``` + +迭代法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + que = deque() + que.append(root) + res = 1 + + while que: + for _ in range(len(que)): + node = que.popleft() + # 当左右孩子都为空的时候,说明是最低点的一层了,退出 + if not node.left and not node.right: + return res + if node.left is not None: + que.append(node.left) + if node.right is not None: + que.append(node.right) + res += 1 + return res +``` + Go: @@ -208,4 +250,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file