Skip to content

Commit be88d00

Browse files
committed
add test case and clean code for BFS python
1 parent fecbbcc commit be88d00

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

Python/Binary_Tree_Level_Order_Traversal.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,26 @@ def levelOrder(root):
77
#Return empty list if the root node is null
88
if not root: return []
99
#vaiable to hold final result, queue of nodes and current level of tree
10-
r, q, c = [[]], [root], []
10+
order, queue, nextQueue = [], [root], []
1111
#While the queue is not empty
12-
while q:
12+
while queue:
1313
#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)):
1715
#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

Comments
 (0)