DDSA Solutions

Left View of Binary Tree

Time: O(n)
Space: O(n)
Advertisement

Intuition

BFS level order: first node of each level is visible from left. Or DFS with level tracking: first visit at each level is left view.

Algorithm

  1. 1BFS: for each level, add the first node's value to result.
  2. 2Or DFS: pass level. If level == result.size(), add current node value (first visit at this level).

Common Pitfalls

  • DFS should visit left child first to ensure leftmost node is recorded first.
Left View of Binary Tree.java
Java
// Approach: BFS level-order traversal. For each level, collect only the first (leftmost) node.
// Time: O(n) Space: O(n)
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int item) {
        data = item;
        left = right = null;
    }
}

class Tree {
    ArrayList<Integer> ans = new ArrayList<>();

    ArrayList<Integer> leftView(Node root) {
        add(root, 0);

        return ans;
    }

    void add(Node root, int count) {
        if (root == null)
            return;

        if (ans.size() <= count)
            ans.add(root.data);

        add(root.left, count + 1);
        add(root.right, count + 1);
    }
}
Advertisement
Was this solution helpful?