classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defrecoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ nodes = []
defdfs(node: Optional[TreeNode]) -> None: ifnot node: return dfs(node.left) nodes.append(node) dfs(node.right) dfs(root) x = None y = None for i inrange(len(nodes) - 1): if nodes[i].val > nodes[i + 1].val: ifnot x: # if x is None, then this is the first time we see a violation x = nodes[i] y = nodes[i + 1] # y is the second violation x.val, y.val = y.val, x.val