LeetCode99 恢复二叉搜索树(Morris中序遍历)
Morris中序遍历 + 记录逆序对
# Definition for a binary tree node.
# 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.
"""
x, y, pre, cur = None, None, None, None
while root:
if root.left:
cur = root.left
while cur.right and cur.right != root:
cur = cur.right
if cur.right is None:
cur.right, root = root, root.left
else:
if pre and pre.val > root.val:
y = root
if x is None: x = pre
pre, cur.right, root = root, None, root.right
else:
if pre and pre.val > root.val:
y = root
if x is None: x = pre
pre, root = root, root.right
if x and y: x.val, y.val = y.val, x.val