Practice › Trees
Left View of a Binary Tree
Medium · Trees · Asked at Amazon, Microsoft, Flipkart, Paytm
Print the left view: the first (leftmost) node of every level, from top to bottom.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The left view, space-separated.
Constraints
- 1 ≤ number of nodes ≤ 10^4
Level order traversal: print the first node of each level. Or DFS (left child first) and print a node when its depth is seen for the first time.
Example 1
Input
9 1 2 3 4 5 6 7 -1 8
Output
1 2 4 8
Example 2
Input
3 1 -1 3
Output
1 3
Hints
- The left view contains exactly one node per level.
- In a level-order traversal, take the first node of each level.
Approach
BFS level by level: record the size of the queue at the start of a level, process that many nodes, and output the first one. (A DFS that visits the left child first and prints a node the first time its depth appears works too.)
Complexity: O(n) time · O(width) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// Build a tree from level order where -1 means "no node".
Node *readTree() {
int k;
cin >> k;
vector<long long> v(k);
for (auto &x : v) cin >> x;
if (k == 0 || v[0] == -1) return nullptr;
Node *root = new Node(v[0]);
queue<Node *> q;
q.push(root);
int i = 1;
while (!q.empty() && i < k) {
Node *cur = q.front();
q.pop();
if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
i++;
}
return root;
}
int main() {
Node *root = readTree();
vector<long long> out;
queue<Node *> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
Node *n = q.front();
q.pop();
if (i == 0) out.push_back(n->val);
if (n->left) q.push(n->left);
if (n->right) q.push(n->right);
}
}
for (size_t i = 0; i < out.size(); i++) cout << out[i] << (i + 1 < out.size() ? " " : "\n");
return 0;
}Python solution
import sys
from collections import deque
sys.setrecursionlimit(100000)
class Node:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build_tree(v):
"""Build a tree from level order where -1 means "no node"."""
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < len(v):
cur = q.popleft()
if i < len(v) and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < len(v) and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]
out, level = [], [root]
while level:
out.append(level[0].val)
level = [c for n in level for c in (n.left, n.right) if c]
print(*out)Java solution
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// Build a tree from level order where -1 means "no node".
static Node readTree(Scanner sc) {
int k = sc.nextInt();
long[] v = new long[k];
for (int i = 0; i < k; i++) v[i] = sc.nextLong();
if (k == 0 || v[0] == -1) return null;
Node root = new Node(v[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
i++;
}
return root;
}
public static void main(String[] args) {
Node root = readTree(new Scanner(System.in));
StringBuilder sb = new StringBuilder();
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
Node n = q.poll();
if (i == 0) sb.append(sb.length() > 0 ? " " : "").append(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
System.out.println(sb);
}
}Solve Left View of a Binary Tree online · All practice problems