@@ -7,19 +7,26 @@ def levelOrder(root):
7
7
#Return empty list if the root node is null
8
8
if not root : return []
9
9
#vaiable to hold final result, queue of nodes and current level of tree
10
- r , q , c = [[] ], [root ], []
10
+ order , queue , nextQueue = [], [root ], []
11
11
#While the queue is not empty
12
- while q :
12
+ while queue :
13
13
#For every node in the queue
14
- for i in range (len (q )):
15
- #Append the node to the last list in the result list
16
- r [- 1 ] += [q [i ].val ]
14
+ for node in range (len (queue )):
17
15
#If that node has a left child, append to current list, then same for right child
18
- c = c + [q [i ].left ] if q [i ].left else c
19
- c = c + [q [i ].right ] if q [i ].right else c
20
- #Let queue be the current traversal level nodes, and current level resets to empty list
21
- q , c = c , []
22
- #Append empty list to result (for next level) if queue is non empty
23
- r = r + [[]] if q else r
24
- return r
25
-
16
+ if queue [node ].left : nextQueue += [queue [node ].left ]
17
+ if queue [node ].right : nextQueue += [queue [node ].right ]
18
+ #Now we append the current queue to the order (the lambda is just there to turn the TreeNode objects to their values)
19
+ order += [list (map (lambda x : x .val , queue ))]
20
+ queue , nextQueue = nextQueue , []
21
+ return order
22
+
23
+ def main ():
24
+ tree = TreeNode (6 )
25
+ tree .left = TreeNode (3 )
26
+ tree .right = TreeNode (12 )
27
+ tree .left .right = TreeNode (4 )
28
+ tree .right .right = TreeNode (14 )
29
+
30
+ print (levelOrder (tree ))
31
+
32
+ main ()
0 commit comments