forked from OmkarPathak/Data-Structures-using-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
P01_BreadthFirstTraversal.py
45 lines (38 loc) · 1.03 KB
/
P01_BreadthFirstTraversal.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
# Author: OMKAR PATHAK
class Node(object):
def __init__(self, data = None):
self.leftChild = None
self.rightChild = None
self.data = data
def height(node):
if node is None:
return 0
else:
leftHeight = height(node.leftChild)
rightHeight = height(node.rightChild)
if leftHeight > rightHeight:
return leftHeight + 1
else:
return rightHeight + 1
def breadthFirstTraversal(root):
if root == None:
return 0
else:
h = height(root)
for i in range(1, h + 1):
printBFT(root, i)
def printBFT(root, level):
if root is None:
return
else:
if level == 1:
print(root.data, end = ' ')
elif level > 1:
printBFT(root.leftChild, level - 1)
printBFT(root.rightChild, level - 1)
if __name__ == '__main__':
root = Node(1)
root.leftChild = Node(2)
root.rightChild = Node(3)
root.leftChild.leftChild = Node(4)
breadthFirstTraversal(root)