-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathtree_traversal.py
118 lines (89 loc) · 2.67 KB
/
tree_traversal.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
from __future__ import annotations
class Node:
def __init__(self, *children: Node, data=None):
self.children = list(children)
self.data = data
def __repr__(self):
return f'({self.data})'
# initial recursive implementation
def print_parent_then_children(node: Node):
print(node)
for child in node.children:
print_parent_then_children(child)
# first try using stack
def print_parent_then_children(node: Node):
stack = [node]
while stack:
node = stack.pop()
print(node)
for child in node.children:
stack.append(child)
# fixed issue with order of pushing onto stack
def print_parent_then_children(node: Node):
stack = [node]
while stack:
node = stack.pop()
print(node)
for child in reversed(node.children):
stack.append(child)
# recursive implementation with max depth
def print_parent_then_children(node: Node, max_depth=-1):
print(node)
if max_depth == 0:
return
for child in node.children:
print_parent_then_children(child, max_depth - 1)
# stack version with max depth
def print_parent_then_children(node: Node, max_depth=-1):
stack = [(node, max_depth)]
while stack:
node, max_depth = stack.pop()
print(node)
if max_depth == 0:
continue
for child in reversed(node.children):
stack.append((child, max_depth - 1))
# factor out the iteration
def walk_parent_then_children(node: Node, max_depth=-1):
stack = [(node, max_depth)]
while stack:
node, max_depth = stack.pop()
yield node
if max_depth == 0:
continue
for child in reversed(node.children):
stack.append((child, max_depth - 1))
# decoupled implementation
def print_parent_then_children(node: Node, max_depth=-1):
for node in walk_parent_then_children(node, max_depth):
print(node)
# root -> child 0 -> child 1 -> ...
def long_tree_example():
root = Node(data="root")
node = root
for n in range(1000):
new = Node(data=f"child {n}")
node.children.append(new)
node = new
print_parent_then_children(root)
# root
# child 0 child 1
# 0-0 0-1 0-2
def small_example():
root = Node(
Node(
Node(data="child 0-0"),
Node(data="child 0-1"),
Node(data="child 0-2"),
data="child 0",
),
Node(data="child 1"),
data="root",
)
print_parent_then_children(root)
print(list(walk_parent_then_children(root, max_depth=1)))
def main():
small_example()
long_tree_example()
if __name__ == '__main__':
main()