Skip to content

Commit 71afa5c

Browse files
authored
Merge pull request #707 from Manasi2001/issue-706
BST Level Order Traversal
2 parents 624af4c + 497779c commit 71afa5c

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
'''
2+
Aim: To perform level-order traversal on a BST.
3+
4+
'''
5+
6+
# initializing the tree
7+
class Node:
8+
def __init__(self,data):
9+
self.right=self.left=None
10+
self.data = data
11+
12+
class Solution:
13+
# inserting node
14+
def insert(self,root,data):
15+
if root==None:
16+
return Node(data)
17+
else:
18+
if data<=root.data:
19+
cur=self.insert(root.left,data)
20+
root.left=cur
21+
else:
22+
cur=self.insert(root.right,data)
23+
root.right=cur
24+
return root
25+
# performing level order traversal
26+
# the values will be printed according to the level they are in
27+
def levelOrder(self,root):
28+
if root is None:
29+
return
30+
q = []
31+
q.append(root)
32+
while len(q) !=0:
33+
p = q.pop(0)
34+
print(p.data, end=' ')
35+
if p.left is not None:
36+
q.append(p.left)
37+
if p.right is not None:
38+
q.append(p.right)
39+
return q
40+
41+
# getting the input
42+
T=int(input())
43+
myTree=Solution()
44+
root=None
45+
for i in range(T):
46+
data=int(input())
47+
root=myTree.insert(root,data)
48+
# printing the result
49+
myTree.levelOrder(root)
50+
51+
'''
52+
53+
COMPLEXITY:
54+
55+
Time Complexity -> O(N)
56+
Space Complexity -> O(N)
57+
58+
Sample Input:
59+
6
60+
3
61+
5
62+
4
63+
7
64+
2
65+
1
66+
Sample Output:
67+
3 2 5 1 4 7
68+
69+
Explaination:
70+
The BST looks something like this:
71+
72+
3 Level 0
73+
2 5 Level 1
74+
1 4 7 Level 2
75+
76+
So, starting from level 0 and going to level 2, traversal will look like: 3, 2 5, 1 4 7.
77+
78+
'''

0 commit comments

Comments
 (0)