Python程序:移除BST中不在指定范围内的所有节点
假设我们有一个BST,以及两个值low和high,我们需要删除所有不在[low, high](包含)范围内的节点。
例如,输入为:
low = 7, high = 10,则输出为:
为了解决这个问题,我们将遵循以下步骤:
- 定义一个函数solve()。该函数将接收根节点root、low和high作为参数。
- 如果root为空,则
- 返回
- 如果low > 根节点的值,则
- 返回solve(root的右子树, low, high)
- 如果high < 根节点的值,则
- 返回solve(root的左子树, low, high)
- root的右子树 := solve(root的右子树, low, high)
- root的左子树 := solve(root的左子树, low, high)
- 返回root
让我们来看下面的实现,以便更好地理解:
示例
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,
广告