-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathBST_Level_Order_Traversal.py
78 lines (66 loc) · 1.67 KB
/
BST_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
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
'''
Aim: To perform level-order traversal on a BST.
'''
# initializing the tree
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
# inserting node
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
# performing level order traversal
# the values will be printed according to the level they are in
def levelOrder(self,root):
if root is None:
return
q = []
q.append(root)
while len(q) !=0:
p = q.pop(0)
print(p.data, end=' ')
if p.left is not None:
q.append(p.left)
if p.right is not None:
q.append(p.right)
return q
# getting the input
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
# printing the result
myTree.levelOrder(root)
'''
COMPLEXITY:
Time Complexity -> O(N)
Space Complexity -> O(N)
Sample Input:
6
3
5
4
7
2
1
Sample Output:
3 2 5 1 4 7
Explaination:
The BST looks something like this:
3 Level 0
2 5 Level 1
1 4 7 Level 2
So, starting from level 0 and going to level 2, traversal will look like: 3, 2 5, 1 4 7.
'''