用 Python 编写程序从 BST 中删除不在范围内的所有节点
pythonserver side programmingprogramming更新于 2026/1/10 17:16:17
假设我们有一个 BST,有两个值,低和高,我们必须删除所有不在 [低,高](含)之间的节点。
因此,如果输入如下

low = 7 high = 10,则输出将是

为了解决这个问题,我们将遵循以下步骤 −
- 定义一个函数solve()。这将获取root,low,high
- 如果root为空,则
- 返回
- 如果low >根的数据,则
- 返回 solve(根的右侧,低,高)
- 如果高 < 根的数据,则
- 返回 solve(根的左侧,低,高)
- 根的右侧 := solve(根的右侧,低,高)
- 根的左侧 := solve(根的左侧,低,高)
- 返回根
让我们看看下面的实现以便更好地理解 −
示例
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) class Solution: def solve(self, root, low, high): if not root: return if low > root.data: return self.solve(root.right,low,high) if high < root.data: return self.solve(root.left,low,high) root.right = self.solve(root.right,low,high) root.left = self.solve(root.left,low,high) return root ob = Solution() root = TreeNode(5) root.left = TreeNode(1) root.right = TreeNode(9) root.right.left = TreeNode(7) root.right.right = TreeNode(10) root.right.left.left = TreeNode(6) root.right.left.right = TreeNode(8) low = 7 high = 10 ret = ob.solve(root, low, high) print_tree(ret)
输入
root = TreeNode(5) root.left = TreeNode(1) root.right = TreeNode(9) root.right.left = TreeNode(7) root.right.right = TreeNode(10) root.right.left.left = TreeNode(6) root.right.left.right = TreeNode(8) low = 7 high = 10
输出
7, 8, 9, 10,
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

