-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19.Binary_Tree(BFS).py
More file actions
65 lines (49 loc) · 1.19 KB
/
19.Binary_Tree(BFS).py
File metadata and controls
65 lines (49 loc) · 1.19 KB
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
class ArrayQueue:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def enqueue(self, item):
self.data.append(item)
def dequeue(self):
return self.data.pop(0)
def peek(self):
return self.data[0]
class Node:
def __init__(self, item):
self.data = item
self.left = None
self.right = None
class BinaryTree:
def __init__(self, r):
self.root = r
def bft(self):
traversal = []
q = ArrayQueue()
if self.root:
q.enqueue(self.root)
while not q.isEmpty():
pre = q.dequeue()
traversal.append(pre.data)
if pre.left:
q.enqueue(pre.left)
if pre.right:
q.enqueue(pre.right)
return traversal
# node1 = Node(1)
# node2 = Node(2)
# node3 = Node(3)
# node4 = Node(4)
# node5 = Node(5)
# node6 = Node(6)
# node7 = Node(7)
# node1.left = node2
# node1.right = node3
# node2.left = node4
# node2.right = node5
# node3.left = node6
# node3.right = node7
# binary_tree = BinaryTree(node1)
# print(binary_tree.bft())