forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_tree_to_list.py
More file actions
37 lines (31 loc) · 771 Bytes
/
bin_tree_to_list.py
File metadata and controls
37 lines (31 loc) · 771 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
from tree.tree import TreeNode
def bin_tree_to_list(root):
"""
type root: root class
"""
if not root:
return root
root = bin_tree_to_list_util(root)
while root.left:
root = root.left
return root
def bin_tree_to_list_util(root):
if not root:
return root
if root.left:
left = bin_tree_to_list_util(root.left)
while left.right:
left = left.right
left.right = root
root.left = left
if root.right:
right = bin_tree_to_list_util(root.right)
while right.left:
right = right.left
right.left = root
root.right = right
return root
def print_tree(root):
while root:
print(root.val)
root = root.right