-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path99. Recover Binary Search Tree.py
43 lines (33 loc) · 1.15 KB
/
99. Recover Binary Search Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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.
"""
prev, start, first = None, None, None
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if not prev:
prev = node
elif not first:
if prev.val > node.val:
start = prev
first = node
else:
if prev.val > node.val:
start.val,node.val = node.val,start.val
return None
prev = node
node = node.right
if start and first:
start.val, first.val = first.val, start.val
return None