Python程序:将近似BST转换为精确BST
假设我们有一棵二叉树,它几乎是一棵二叉搜索树。只有两个节点的值被交换了。我们必须纠正它并返回二叉搜索树。
因此,如果输入是这样的:
那么输出将是:
为了解决这个问题,我们将遵循以下步骤:
- prev_node := null,min_node := null,max_node := null
- found_one := False
- 对于根节点的中序遍历中的每个节点,执行:
- 如果prev_node不为空,则:
- 如果节点的值 < prev_node的值,则:
- 如果min_node为空或节点的值 < min_node的值,则:
- min_node := 节点
- 如果max_node为空或max_node的值 < prev_node的值,则:
- max_node := prev_node
- 如果found_one为true,则:
- 退出循环
- 否则:
- found_one := True
- 如果min_node为空或节点的值 < min_node的值,则:
- prev_node := 节点
- 如果节点的值 < prev_node的值,则:
- 如果prev_node不为空,则:
- 交换min_node和max_node的值
- 返回根节点
让我们看看下面的实现,以便更好地理解:
示例
class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.val, end = ', ') print_tree(root.right) def __iter__(self): if self.left: for node in self.left: yield node yield self if self.right: for node in self.right: yield node setattr(TreeNode, "__iter__", __iter__) class Solution: def solve(self, root): prev_node = None min_node = None max_node = None found_one = False for node in root: if prev_node: if node.val < prev_node.val: if min_node is None or node.val < min_node.val: min_node = node if max_node is None or max_node.val < prev_node.val: max_node = prev_node if found_one: break else: found_one = True prev_node = node min_node.val, max_node.val = max_node.val, min_node.val return root ob = Solution() root = TreeNode(3) root.left = TreeNode(6) root.right = TreeNode(8) root.right.left = TreeNode(2) root.right.right = TreeNode(9) print_tree(ob.solve(root))
输入
root = TreeNode(3) root.left = TreeNode(6) root.right = TreeNode(8) root.right.left = TreeNode(2) root.right.right = TreeNode(9)
输出
2, 3, 6, 8, 9,
广告