-
Notifications
You must be signed in to change notification settings - Fork 43
/
increasing-order-search-tree.py
120 lines (112 loc) · 3.05 KB
/
increasing-order-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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82349263
# 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 increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
array = self.inOrder(root)
if not array:
return None
newRoot = TreeNode(array[0])
curr = newRoot
for i in range(1, len(array)):
curr.right =TreeNode(array[i])
curr = curr.right
return newRoot
def inOrder(self, root):
if not root:
return []
array = []
array.extend(self.inOrder(root.left))
array.append(root.val)
array.extend(self.inOrder(root.right))
return array
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82349263
# 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 increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
res = self.inOrder(root)
if not res:
return
dummy = TreeNode(-1)
cur = dummy
for node in res:
node.left = node.right = None
cur.right = node
cur = cur.right
return dummy.right
def inOrder(self, root):
if not root:
return []
res = []
res.extend(self.inOrder(root.left))
res.append(root)
res.extend(self.inOrder(root.right))
return res
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/82349263
# 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 increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
dummy = TreeNode(-1)
self.prev = dummy
self.inOrder(root)
return dummy.right
def inOrder(self, root):
if not root:
return None
self.inOrder(root.left)
root.left = None
self.prev.right = root
self.prev = self.prev.right
self.inOrder(root.right)
# V2
# Time: O(n)
# Space: O(h)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def increasingBSTHelper(root, tail):
if not root:
return tail
result = increasingBSTHelper(root.left, root)
root.left = None
root.right = increasingBSTHelper(root.right, tail)
return result
return increasingBSTHelper(root, None)