Left View of Binary Tree
You are given the root of a binary tree. Your task is to return the left view of the binary tree. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left side.
If the tree is empty, return an empty list.
Examples :
Input: root[] = [1, 2, 3, 4, 5, N, N]
Output: [1, 2, 4]
Explanation: From the left side of the tree, only the nodes 1, 2, and 4 are visible.
Input: root[] = [1, 2, 3, N, N, 4, N, N, 5, N, N]
Output: [1, 2, 4, 5]
Explanation: From the left side of the tree, the nodes 1, 2, 4, and 5 are visible.
Input: root[] = [N]
Output: []
Approach 1: Level Order Traversal (BFS)
We can do a level-order traversal using a queue, and print the first node of each level.
✏️ Notes:
-
Use a
Queue<Node>
for BFS (level order traversal). -
At each level:
-
Get the number of nodes in that level:
int size = q.size()
-
Loop from
i = 0
toi < size
:-
If
i == 0
→ this is the first node at this level → add to result -
Add the
left
andright
child (if not null) to the queue
-
-
📘 Summary Notes:
-
Traverse level by level.
-
Track the first node of each level.
-
Use a queue to hold nodes for BFS.
-
Add left child first, then right, to ensure left view priority.
Comments
Post a Comment