-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaive_tree.py
60 lines (52 loc) · 1.58 KB
/
naive_tree.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
from collections import deque
class NaiveBinaryTree():
def __init__(self):
self.head = None
def __str__(self):
"""
Print a pre order traversal.
"""
output = self.pre_order_traversal()
str_output = '[' + ", ".join(map(str, output)) + ']'
return str_output
def pre_order_traversal(self):
output = []
def recur(node):
if node:
output.append(node.value)
recur(node.left)
recur(node.right)
recur(self.head)
return output
def in_order_traversal(self):
output = []
def recur(node):
if node:
recur(node.left)
output.append(node.value)
recur(node.right)
recur(self.head)
return output
def post_order_traversal(self):
output = []
def recur(node):
if node:
recur(node.left)
recur(node.right)
output.append(node.value)
recur(self.head)
return output
def level_order_traversal(self):
output = []
queue = deque([self.head])
while queue:
output.extend(list(map(lambda n: n.value, list(queue))))
next_level = deque()
while queue:
current = queue.popleft()
if current.left:
next_level.append(current.left)
if current.right:
next_level.append(current.right)
queue = next_level
return output