-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path99_Recover_Binary_Search_Tree.py
More file actions
39 lines (37 loc) · 1.06 KB
/
99_Recover_Binary_Search_Tree.py
File metadata and controls
39 lines (37 loc) · 1.06 KB
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
# 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.
"""
def inorder(root):
if root:
inorder(root.left)
l.append(root)
inorder(root.right)
# l=[]
# inorder(root)
# p=sorted(n.val for n in l)
# for i in range(len(p)):
# l[i].val=p[i]
# return root
f=p=s=None
def inorder(root):
nonlocal p,f,s
if root:
inorder(root.left)
if p and p.val>root.val:
if not f:
f=p
s=root
p=root
inorder(root.right)
inorder(root)
if f and s:
f.val,s.val=s.val,f.val
return root