-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary_tree_level_order_traversal.py
55 lines (46 loc) · 1.71 KB
/
binary_tree_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
'''
Question: https://leetcode.com/problems/binary-tree-level-order-traversal/
'''
import collections
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
'''
Use BFS for level order traversal
TC: O(n)
SC: O(n)
'''
# to store the final result
result = []
# to store the nodes levelwise (BFS)
queue = collections.deque()
# append (from right) the root to start with BFS algorithm
queue.append(root)
# while the `queue` still has nodes
while queue:
# to traverse nodes only in the current level
qLen = len(queue)
# to store nodes in the current level
level = []
# iterate only over nodes in the current level
for i in range(qLen):
# pop the node from the queue from RHS (FIFO)
node = queue.popleft()
# only add to level if node is non-NULL
if node:
# append the current node to the current level list
level.append(node.val)
# append the left child of the current node to the queue
queue.append(node.left)
# append the right child of the current node to the queue
queue.append(node.right)
# only append to result if the level has nodes in it
if level:
result.append(level)
return result