-
Notifications
You must be signed in to change notification settings - Fork 613
/
99.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
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
first, second, prev = None, None, None
def inorder(root):
if root:
inorder(root.left)
if prev is not None and root.val < prev.val:
if first is None:
first = root
else:
second = root
prev = root
inorder(root.right)
inorder(root)
if first and second:
first.val, second.val = second.val, first.val