1
+ ##==================================
2
+ ## Leetcode
3
+ ## Student: Vandit Jyotindra Gajjar
4
+ ## Year: 2020
5
+ ## Problem: 102
6
+ ## Problem Name: Binary Tree Level Order Traversal
7
+ ##===================================
8
+ #
9
+ #Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
10
+ #
11
+ #For example:
12
+ #Given binary tree [3,9,20,null,null,15,7],
13
+ # 3
14
+ # / \
15
+ # 9 20
16
+ # / \
17
+ # 15 7
18
+ #return its level order traversal as:
19
+ #[
20
+ # [3],
21
+ # [9,20],
22
+ # [15,7]
23
+ #]
24
+ import queue
25
+ class Solution :
26
+ def levelOrder (self , root ):
27
+ tmp = [] #Initialize tmp empty list
28
+ q = queue .Queue () #Initialize queue
29
+ if root is None : #Condition-check: If root is empty
30
+ return None #Return nothing
31
+ q .put (root ) #Put root in our queue
32
+ while not q .empty (): #While queue is not empty
33
+ array = [] #Initialize an empty array for levelorder nodes
34
+ size = q .qsize () #Get the size of queue
35
+ while size != 0 : #Loop till size gets zero
36
+ curr = q .get () #Initialize curr which takes the value we have put
37
+ array .append (curr .val ) #Append that curr's value in array
38
+ if curr .left is not None : #Condition-check: If we have left subtree or child
39
+ q .put (curr .left ) #We simply add that curr's left in queue
40
+ if curr .right is not None : #Condition-check: If we have right subtree or child
41
+ q .put (curr .right ) #We simply add that curr's right in queue
42
+ size -= 1 #Reduce size by 1
43
+ if len (array ) != 0 : #Condition-check: If the array's length is not equal to zero
44
+ tmp .append (array ) #We append that array in our tmp array, which we'll return
45
+ return tmp #Finally we'll return tmp
46
+
0 commit comments