99. 恢复二叉搜索树
题目描述
解题思路
根据题意,中序遍历找到第一个升序顺序错乱最大值节点,和最后一个升序顺序错乱的最小值节点。然后交换两个节点val即可。
代码实现
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.pre = None
self.first_error_node = None
self.last_error_node = None
def helper(root):
if not root:
return
helper(root.left)
if self.pre and self.pre.val > root.val:
self.last_error_node = root
if not self.first_error_node:
self.first_error_node = self.pre
self.pre = root
helper(root.right)
helper(root)
if self.first_error_node and self.last_error_node:
self.first_error_node.val, self.last_error_node.val = self.last_error_node.val, self.first_error_node.val