- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path99.py
53 lines (43 loc) · 1.01 KB
/
99.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
44
45
46
47
48
49
50
51
52
53
'''
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
classSolution(object):
defrecoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
first, second, prev=None, None, None
definorder(root):
ifroot:
inorder(root.left)
ifprevisnotNoneandroot.val<prev.val:
iffirstisNone:
first=root
else:
second=root
prev=root
inorder(root.right)
inorder(root)
iffirstandsecond:
first.val, second.val=second.val, first.val