-
Notifications
You must be signed in to change notification settings - Fork 17
/
LevelOrderTraversal.py
125 lines (63 loc) · 2.13 KB
/
LevelOrderTraversal.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
Level order traversal
Send Feedback
For a given a Binary Tree of type integer, print it in a level order fashion where each level will be printed on a new line.
Elements on every level will be printed in a linear fashion and a single space will separate them.
"""
from sys import stdin, setrecursionlimit
import queue
setrecursionlimit(10 ** 6)
#Following is the structure used to represent the Binary Tree Node
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printLevelWise(root):
#Your code goes here
if root is None :
return
pendingNodes = queue.Queue()
pendingNodes.put(root)
pendingNodes.put(None)
while not pendingNodes.empty():
frontNode = pendingNodes.get()
if frontNode is None :
print()
if not pendingNodes.empty() :
pendingNodes.put(None)
else :
print(frontNode.data, end = " ")
if frontNode.left is not None :
pendingNodes.put(frontNode.left)
if frontNode.right is not None :
pendingNodes.put(frontNode.right)
#Taking level-order input using fast I/O method
def takeInput():
levelOrder = list(map(int, stdin.readline().strip().split(" ")))
start = 0
length = len(levelOrder)
if length == 1 :
return None
root = BinaryTreeNode(levelOrder[start])
start += 1
q = queue.Queue()
q.put(root)
while not q.empty():
currentNode = q.get()
leftChild = levelOrder[start]
start += 1
if leftChild != -1:
leftNode = BinaryTreeNode(leftChild)
currentNode.left =leftNode
q.put(leftNode)
rightChild = levelOrder[start]
start += 1
if rightChild != -1:
rightNode = BinaryTreeNode(rightChild)
currentNode.right =rightNode
q.put(rightNode)
return root
# Main
root = takeInput()
printLevelWise(root)