-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathp17_12.py
58 lines (40 loc) · 1.32 KB
/
p17_12.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
from typing import Tuple
# Method: Recursive call, returning left and right edges of result linked list
# Time: O(n)
# Space: O(d)
# Where d = depth of BST
class BiNode:
def __init__(self, val):
self.val = val
self.node1 = None
self.node2 = None
def flatten_binary_tree(root: BiNode):
left_side, _ = flat_helper(root)
return left_side
def flat_helper(root: BiNode) -> Tuple[BiNode, BiNode]:
left_edge = root
right_edge = root
if root.node1:
left_edge_left, left_edge_right = flat_helper(root.node1)
root.node1 = left_edge_right
left_edge_right.node2 = root
left_edge = left_edge_left
if root.node2:
right_edge_left, right_edge_right = flat_helper(root.node2)
root.node2 = right_edge_left
right_edge_left.node1 = root
right_edge = right_edge_right
return (left_edge, right_edge)
if __name__ == "__main__":
root = BiNode(20)
root.node1 = BiNode(10)
root.node1.node1 = BiNode(5)
root.node2 = BiNode(25)
root.node2.node1 = BiNode(22)
root.node2.node1.node2 = BiNode(23)
root.node2.node1.node1 = BiNode(21)
list_start = flatten_binary_tree(root)
list_elem_now = list_start
while list_elem_now.node2:
print(list_elem_now.val)
list_elem_now = list_elem_now.node2