File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(n) -> visit each node exactly once.
2+ # Space Complexity: O(n) -> in the worst case, the queue holds all nodes at the last level.
3+
4+ class Solution :
5+ def levelOrder (self , root : Optional [TreeNode ]) -> List [List [int ]]:
6+
7+ # list to store level order traversal.
8+ ans = []
9+
10+ # if the tree is empty, return an empty list.
11+ if root is None :
12+ return ans
13+
14+ # queue to process nodes level by level.
15+ q = deque ([root ])
16+
17+ while q :
18+ # list to store values of nodes at the current level.
19+ t = []
20+
21+ # process all nodes at this level.
22+ for _ in range (len (q )):
23+ # pop the first node from the queue.
24+ node = q .popleft ()
25+ # add node's value to the list.
26+ t .append (node .val )
27+
28+ if node .left :
29+ q .append (node .left )
30+ if node .right :
31+ q .append (node .right )
32+
33+ # add current level values to the result list.
34+ ans .append (t )
35+
36+ return ans
You can’t perform that action at this time.
0 commit comments