-
Notifications
You must be signed in to change notification settings - Fork 218
/
Copy pathLevel_Order_Traversal(BFS).py
64 lines (48 loc) · 1.36 KB
/
Level_Order_Traversal(BFS).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
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# ____________Recursive Approach_________
# def printLevelorder(root):
# h = height(root)
# for i in range(1, h+1):
# printCurrentLevel(root, i)
# def printCurrentLevel(root, level):
# if root is None:
# return
# if level == 1:
# print(root.data, end=" ")
# else:
# printCurrentLevel(root.left, level-1)
# printCurrentLevel(root.right, level-1)
# def height(node):
# if node:
# lheight = height(node.left)
# rheight = height(node.right)
# if lheight > rheight:
# return lheight + 1
# else:
# return rheight + 1
# return 0
# ___________Queue Method____________
def printLevelorder(root):
if root is None:
return
queue = []
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
print(node.data, end = " ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# Driver's program
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Level order traversal of binary tree is - ")
printLevelorder(root)