6. Left View of Binary Tree
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You are given the root of a binary tree. Your task is to return the left view of the binary tree. The left view is defined as the set of nodes visible when the tree is observed from the left side.
If the tree is empty, return an empty list.
๐ Examples
Example 1:
Input:
root[] = [1, 2, 3, 4, 5, N, N]
Output:
[1, 2, 4]
Explanation:
From the left side of the tree, the visible nodes are: 1 (level 0), 2 (level 1), and 4 (level 2).
Example 2:
Input:
root[] = [1, 2, 3, N, N, 4, N, N, 5, N, N]
Output:
[1, 2, 4, 5]
Explanation:
Only one node at each level is visible from the left side, namely: 1, 2, 4, and 5.
Example 3:
Input:
root[] = [N]
Output:
[]
๐ Constraints:
$0 \leq$ Number of nodes $\leq 10^6$
$0 \leq$ Node $\rightarrow$ data $\leq 10^5$
โ
My Approach
BFS Level Order Traversal
We use level-order traversal (BFS) to traverse the binary tree. For each level, we keep track of the first node encountered and add it to the result list.
Algorithm Steps:
Initialize an empty queue and push the root node.
For each level in the tree:
Record the first node's value at the front of the queue.
Add all children (left first, then right) to the queue.
Repeat for all levels and return the result list.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), as we visit every node exactly once during level-order traversal.
Expected Auxiliary Space Complexity: O(W), where W is the maximum width of the binary tree (maximum number of nodes at any level due to the queue used in BFS).
๐ง Code (C++)
class Solution {
public:
vector<int> leftView(Node *root) {
if (!root) return {};
vector<int> res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
Node* cur = q.front(); q.pop();
if (i == 0) res.push_back(cur->data);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
return res;
}
};
๐งโ๐ป Code (Java)
class Solution {
ArrayList<Integer> leftView(Node root) {
if (root == null) return new ArrayList<>();
ArrayList<Integer> res = new ArrayList<>();
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
Node cur = q.poll();
if (i == 0) res.add(cur.data);
if (cur.left != null) q.add(cur.left);
if (cur.right != null) q.add(cur.right);
}
}
return res;
}
}
๐ Code (Python)
class Solution:
def LeftView(self, root):
if not root: return []
res, q = [], [root]
while q:
res.append(q[0].data)
q = [child for node in q for child in (node.left, node.right) if child]
return res
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated