Left view
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The left view of a tree is the list you get by standing on the left side and noting the first node you see on each level. It teaches you how to pick one representative per level, which is useful any time you summarise a layered structure.
Practical use cases
- Web app: Org chart preview card. An HR dashboard shows a small card for a department with just one name per management level, so the card stays short. The code walks the chart level by level and keeps only the first person on each row. A 10-level hierarchy becomes a 10-line card.
- Web app: Collapsed comment thread preview. A forum shows a compact preview of a thread: the first reply at each depth, so visitors see how the discussion branches without scrolling. The code keeps the first item it meets at every depth and ignores the rest. The preview stays small however long the thread becomes.
- System: Layout and visibility checks. A layout engine drawing a tree-shaped diagram needs the left edge of each row to work out the left margin. Game engines also keep the first visible object in each row of a scene to decide what hides what. Either way, one pass per level is enough to get the answer.
The story: The Class Photo from the Left Door
Mrs. Sharma's class had a class photo day. The students stood in rows on a set of steps: one student in the front row, two in the next, three behind them, and so on, like a tree opened out. The photographer, Mr. Dutta, stood at the left side door and could only peek in from the side.
"What can you see?" asked Mrs. Sharma. Mr. Dutta thought. "From the left door I see only the first student of each row. The others are hidden behind them." Mira counted: Raju in row one, Zoya in row two, Aarav in row three, and the little one in the last row.
Kabir noticed something funny. "In the last row, there was only one student, and he is standing on the right side. But from the left door he is still visible, because nobody is in front of him in that row!" Mrs. Sharma beamed: "That is exactly why we go row by row, not just down the left edge."
The list of what the left door can see is called the left view of the tree: the first node on every level. It is level-order traversal, picking only the first.
How to spot this problem, and where you need it
You have a layered structure and want a short summary that shows just one entry per level, from one particular side, instead of the entire thing.
Signs you need it
- The task says "what do you see from the left", "first node at each level", or "one per level".
- A preview or summary component must stay short no matter how large the hierarchy grows.
- You find yourself grouping nodes by depth and then keeping only index 0 of every group.
Where to use it in a project
- Compact previews of org charts, category trees and threaded discussions.
- Drawing tools that need the left boundary of every row to set indentation or margins.
The solution
Do a level-order walk with a queue. At the start of each level note how many nodes it has, process that many, and remember only the first one you took out. Alternatively, recurse with a depth number and record a node only if that depth has no answer yet, visiting left children first.
Payoff: Before: a preview with every one of 200 nodes. After: a card with one line per level, such as 8 lines, built in a single pass.
Explain it like I am 8
Stand on the left side of the tree and look across. On every floor of the tree, you can only see the first person from the left, because the others stand behind them. The left view is that list: one person per floor.
How it works, step by step
- Do a level-order (BFS) walk, with a queue.
- At the start of each level, remember
size = queue length: that is how many nodes this level has. - Process exactly
sizenodes, numbering them 0, 1, 2... - The node numbered 0 (the first of the level) goes into the answer.
- Add each node's left then right child to the queue, and go on to the next level.
The code in four languages
PHP
<?php
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public int $val) {}
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree(): TreeNode {
$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->left->left = new TreeNode(4);
$root->left->right = new TreeNode(5);
$root->right->right = new TreeNode(6);
$root->left->right->left = new TreeNode(7);
return $root;
}
// Level by level (like BFS). Keep the first node of every level.
function leftView(?TreeNode $root): array {
if ($root === null) return [];
$view = [];
$queue = [$root];
while ($queue) {
$size = count($queue);
for ($i = 0; $i < $size; $i++) {
$node = array_shift($queue);
if ($i === 0) $view[] = $node->val; // first node of the level
if ($node->left) $queue[] = $node->left;
if ($node->right) $queue[] = $node->right;
}
}
return $view;
}
echo implode(' ', leftView(sampleTree())) . PHP_EOL; // 1 2 4 7JavaScript
class TreeNode {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree() {
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
// Level by level (like BFS). Keep the first node of every level.
function leftView(root) {
if (root === null) return [];
const view = [];
const queue = [root];
while (queue.length) {
const size = queue.length;
for (let i = 0; i < size; i++) {
const node = queue.shift();
if (i === 0) view.push(node.val); // first node of the level
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return view;
}
console.log(leftView(sampleTree()).join(' ')); // 1 2 4 7Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
static TreeNode sampleTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
static String join(List<Integer> xs) {
return xs.stream().map(String::valueOf).collect(Collectors.joining(" "));
}
// Level by level (like BFS). Keep the first node of every level.
static List<Integer> leftView(TreeNode root) {
List<Integer> view = new ArrayList<>();
if (root == null) return view;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == 0) view.add(node.val); // first node of the level
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
return view;
}
public static void main(String[] args) {
System.out.println(join(leftView(sampleTree()))); // 1 2 4 7
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// The example tree: 1
//
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
func sampleTree() *TreeNode {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Right.Left = &TreeNode{Val: 7}
return root
}
// leftView goes level by level (like BFS). It keeps the first node of every level.
func leftView(root *TreeNode) []int {
view := []int{}
if root == nil {
return view
}
queue := []*TreeNode{root}
for len(queue) > 0 {
size := len(queue)
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
if i == 0 {
view = append(view, node.Val) // first node of the level
}
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return view
}
// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
parts := make([]string, len(xs))
for i, v := range xs {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(joinInts(leftView(sampleTree()), " ")) // 1 2 4 7
}Time: O(n) · Extra space: O(w). Every node is visited once; the queue holds at most one level (the widest level, w).
Watch out for
- Only following
node.leftdown the tree. That misses levels where the left side has run out, like level 3 here (the 7). - Forgetting to save the level size, so levels get mixed together.
- Confusing "left view" with "left side-most path". Left view picks the first node of every level, wherever it is.
Quick check
- What is the left view of our example tree?
- 4 2 1 3 6
- 1 2 4
- 1 2 4 7
- 1 3 6 7
- Why does 7 appear in the left view even though it is not on the far left?
- It is a leaf
- It is the only node on its level
- It is the smallest number
- Which traversal idea builds the left view?
- Level order (BFS)
- Inorder
- Postorder