-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbstToDoublyList.py
55 lines (38 loc) · 914 Bytes
/
bstToDoublyList.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
class TreeNode(object):
"""docstring for TreeNode"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class DoublyListNode(object):
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
class Solution(object):
"""docstring for Solution"""
def __init__(self):
self.head = None
self.tail = None
def bstToDoublyList(self,root):
if not root:
return
self.bstToDoublyList(root.left)
node = DoublyListNode(root.val)
#print node.val,head
if not self.head:
self.head = node
self.tail = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
#print head.val
self.bstToDoublyList(root.right)
return self.head
test = TreeNode(2)
test.left = TreeNode(1)
test.right = TreeNode(3)
out = Solution()
res = out.bstToDoublyList(test)
print res.val,res.next.val,res.next.next.val