forked from lilianweng/LeetcodePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST2doubly_llist.py
More file actions
52 lines (38 loc) · 965 Bytes
/
BST2doubly_llist.py
File metadata and controls
52 lines (38 loc) · 965 Bytes
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
#!/usr/bin/env python
'''
Leetcode: Convert Binary Search Tree (BST) to Sorted Doubly-Linked List
'''
from __future__ import division
import random
from BinaryTree import *
def get_tail(node):
while node.right:
node = node.right
return node
def convert(root):
if not root: return None
left_list = convert(root.left)
right_list = convert(root.right)
if left_list:
tail = get_tail(left_list)
tail.right = root
root.left = tail
if right_list:
right_list.left = root
root.right = right_list
if left_list: return left_list
else: return root
if __name__ == '__main__':
print BST
head = convert(BST)
# to right
node = head
while node.right:
print node.value, '->',
node = node.right
print node.value
# to right
while node.left:
print node.value, '<-',
node = node.left
print node.value