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,
廣告