forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover-binary-search-tree.py
75 lines (59 loc) · 1.82 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Time: O(n)
# Space: O(1)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
if self:
serial = []
queue = [self]
while queue:
cur = queue[0]
if cur:
serial.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
serial.append("#")
queue = queue[1:]
while serial[-1] == "#":
serial.pop()
return repr(serial)
else:
return None
class Solution(object):
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
return self.MorrisTraversal(root)
def MorrisTraversal(self, root):
if root is None:
return
broken = [None, None]
pre, cur = None, root
while cur:
if cur.left is None:
self.detectBroken(broken, pre, cur)
pre = cur
cur = cur.right
else:
node = cur.left
while node.right and node.right != cur:
node = node.right
if node.right is None:
node.right =cur
cur = cur.left
else:
self.detectBroken(broken, pre, cur)
node.right = None
pre = cur
cur = cur.right
broken[0].val, broken[1].val = broken[1].val, broken[0].val
return root
def detectBroken(self, broken, pre, cur):
if pre and pre.val > cur.val:
if broken[0] is None:
broken[0] = pre
broken[1] = cur