-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathlevel_order_traversal.py
More file actions
44 lines (31 loc) · 859 Bytes
/
level_order_traversal.py
File metadata and controls
44 lines (31 loc) · 859 Bytes
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
""" Level Order Traversal On Binary Tree
"""
from collections import deque
class Node:
""" class representing node in binary tree """
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def level_order(root):
""" level order traversal of binary tree using queue """
if root is None:
return
queue = deque([root])
while queue:
node = queue.popleft()
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
def main():
""" operational function """
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
level_order(root)
if __name__ == "__main__":
main()