Skip to content

Commit e41728d

Browse files
committed
Solution for 102. Binary Tree Level Order Traversal
1 parent 89fdd8e commit e41728d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""
2+
102. Binary Tree Level Order Traversal
3+
https://leetcode.com/problems/binary-tree-level-order-traversal/
4+
"""
5+
6+
from typing import List, Optional
7+
8+
# Definition for a binary tree node.
9+
class TreeNode:
10+
def __init__(self, val=0, left=None, right=None):
11+
self.val = val
12+
self.left = left
13+
self.right = right
14+
15+
"""
16+
Solution
17+
Breadth First Search (BFS) using Queue
18+
19+
The problem is asking to return the node values at each level of the binary tree.
20+
To solve this problem, we can use BFS algorithm with a queue.
21+
We will traverse the tree level by level and store the node values at each level.
22+
23+
1. Initialize an empty list to store the output.
24+
2. Initialize an empty queue.
25+
3. Add the root node to the queue.
26+
4. While the queue is not empty, do the following:
27+
- Get the size of the queue to know the number of nodes at the current level.
28+
- Initialize an empty list to store the node values at the current level.
29+
- Traverse the nodes at the current level and add the node values to the list.
30+
- If the node has left or right child, add them to the queue.
31+
- Decrease the level size by 1.
32+
- Add the list of node values at the current level to the output.
33+
5. Return the output.
34+
35+
Time complexity: O(N)
36+
- We visit each node once
37+
38+
Space complexity: O(N)
39+
- The maximum number of nodes in the queue is the number of nodes at the last level
40+
- The maximum number of nodes at the last level is N/2
41+
- The output list stores the node values at each level which is N
42+
- Thus, the space complexity is O(N)
43+
44+
"""
45+
class Solution:
46+
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
47+
if root is None:
48+
return
49+
output = []
50+
queue = []
51+
queue.append(root)
52+
53+
while(len(queue) > 0):
54+
level_size = len(queue)
55+
level_output = []
56+
57+
while level_size > 0:
58+
node = queue.pop(0)
59+
level_output.append(node.val)
60+
61+
if node.left is not None:
62+
queue.append(node.left)
63+
if node.right is not None:
64+
queue.append(node.right)
65+
66+
level_size -= 1
67+
68+
output.append(level_output)
69+
70+
return output

0 commit comments

Comments
 (0)