forked from imteekay/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree.py
61 lines (44 loc) · 1.42 KB
/
binary_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
61
from queue import Queue
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child:
self.left_child.insert_left(value)
else:
self.left_child = BinaryTree(value)
def insert_right(self, value):
if self.right_child:
self.right_child.insert_right(value)
else:
self.right_child = BinaryTree(value)
def pre_order(self):
print(self.value)
if self.left_child:
self.left_child.pre_order()
if self.right_child:
self.right_child.pre_order()
def post_order(self):
if self.left_child:
self.left_child.post_order()
if self.right_child:
self.right_child.post_order()
print(self.value)
def in_order(self):
if self.left_child:
self.left_child.in_order()
print(self.value)
if self.right_child:
self.right_child.in_order()
def bfs(self):
queue = Queue()
queue.put(self)
while not queue.empty():
current_node = queue.get()
print(current_node.value)
if current_node.left_child:
queue.put(current_node.left_child)
if current_node.right_child:
queue.put(current_node.right_child)