forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree_Level_Order_Traversal.py
52 lines (37 loc) · 1.12 KB
/
Tree_Level_Order_Traversal.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
# Level Order Traversal of a Tree
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = TreeNode(root)
def level_order_traversal(self, root):
nodes_visited = [root]
path = ''
while len(nodes_visited) > 0:
node = nodes_visited.pop(0)
if node.left:
nodes_visited.append(node.left)
if node.right:
nodes_visited.append(node.right)
path += str(node.val) + ' '
return path
# Creating a tree of the following structure:-
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
tree = Tree(1)
tree.root.left = TreeNode(2)
tree.root.right = TreeNode(3)
tree.root.left.left = TreeNode(4)
tree.root.left.right = TreeNode(5)
tree.root.right.left = TreeNode(6)
tree.root.right.right = TreeNode(7)
# Level Order Traversal
# In level order traversal, every node at the
# same level is visited before moving on to the next.
print(tree.level_order_traversal(tree.root)) # Expected Output:- 1 2 3 4 5 6 7