Left View of Binary Tree

 You are given the root of a binary tree. Your task is to return the left view of the binary tree. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left side.


If the tree is empty, return an empty list.


Examples :


Input: root[] = [1, 2, 3, 4, 5, N, N]


Output: [1, 2, 4]

Explanation: From the left side of the tree, only the nodes 1, 2, and 4 are visible.


Input: root[] = [1, 2, 3, N, N, 4, N, N, 5, N, N]


Output: [1, 2, 4, 5]

Explanation: From the left side of the tree, the nodes 1, 2, 4, and 5 are visible.


Input: root[] = [N]

Output: []


Approach 1: Level Order Traversal (BFS)

We can do a level-order traversal using a queue, and print the first node of each level.


✏️ Notes:

  1. Use a Queue<Node> for BFS (level order traversal).

  2. At each level:

    • Get the number of nodes in that level: int size = q.size()

    • Loop from i = 0 to i < size:

      • If i == 0 → this is the first node at this level → add to result

      • Add the left and right child (if not null) to the queue



📘 Summary Notes:

  • Traverse level by level.

  • Track the first node of each level.

  • Use a queue to hold nodes for BFS.

  • Add left child first, then right, to ensure left view priority.


class Solution {
    // Function to return list containing elements of left view of binary tree.
    ArrayList<Integer> leftView(Node root) {
        ArrayList<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Queue<Node> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            int size = q.size();

            for (int i = 0; i < size; i++) {
                Node front = q.poll();  // ✅ poll inside loop

                if (i == 0) {
                    result.add(front.data);  // ✅ First node of the level
                }

                if (front.left != null) {
                    q.offer(front.left);
                }
                if (front.right != null) {
                    q.offer(front.right);
                }
            }
        }

        return result;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence