Left View of Binary Tree — GeeksforGeeks Solution

Pradeep Suryavanshi
2 min readAug 23, 2024

--

Given a Binary Tree, return Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument. If no left view is possible, return an empty tree.

Left view of following tree is 1 2 4 8.

1
/ \
2 3
/ \ / \
4 5 6 7
\
8

Examples :

Input:
1
/ \
3 2
Output: 1 3
Input:
Output: 10 20 40

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
0 <= Number of nodes <= 10^5
0 <= Data of a node <= 10^5

Solution:

//Function to return a list containing elements of left view of the binary tree.
vector<int> leftView(Node* root) {
vector<int> result;
if (root == NULL) return result;

queue<Node*> q;
q.push(root);

while (!q.empty()) {
int n = q.size();
for (int i = 1; i <= n; i++) {
Node* temp = q.front();
q.pop();

if (i == 1) {
result.push_back(temp->data);
}

if (temp->left != NULL) {
q.push(temp->left);
}
if (temp->right != NULL) {
q.push(temp->right);
}
}
}

return result;
}

--

--