给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树。
示例 1:

输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 的左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。
示例 2:

输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。
思路:
二叉搜索树按中序遍历是一个递增的序列,我们只需找到两个错误的节点即可。
在遍历过程中,不满足递增时,就意味着出现了要交换的点(这种情况共两次,分别对应两个错误的节点)
python
if root.val < self.pre.val:
self.index2 = root
if self.index1 == None:
self.index1 = self.pre
这个交换很巧妙,可以实际演示一遍,index1和index2正好可以记录下两个错误的节点。
代码如下:
python
# Definition for a binary tree node.
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def inorder(root):
if not root:
return
inorder(root.left)
if root.val < self.pre.val:
self.index2 = root
if self.index1 == None:
self.index1 = self.pre
self.pre = root
inorder(root.right)
self.pre = TreeNode(-float('inf'))
self.index1 = None
self.index2 = None
inorder(root)
self.index1.val, self.index2.val = self.index2.val, self.index1.val