-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path897. Increasing Order Search Tree.py
67 lines (53 loc) · 1.82 KB
/
897. 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# Iterative approach
if root == None: return
stack = []
head = None
current = None
temp = root
while temp!= None:
stack.append(temp)
temp = temp.left
while stack:
temp2 = stack.pop()
if head == None:
head = temp2
current = head
else:
current.left = None
current.right = temp2
current = current.right
if temp2.right:
stack.append(temp2.right)
temp2 = temp2.right
while temp2.left!=None:
stack.append(temp2.left)
temp2 = temp2.left
return head
# Recursive approach
traversal = []
def inorder(root, traversal):
if root:
inorder(root.left, traversal)
traversal.append(root)
inorder(root.right, traversal)
return traversal
stack = inorder(root,traversal)
new_root = stack.pop(0)
current = new_root
while stack:
current.left = None
current.right= stack.pop(0)
current = current.right
return new_root