Left View of a Binary Tree

Algorithm Steps

  1. If the binary tree is empty, return an empty list.
  2. Initialize a queue and add the root node.
  3. While the queue is not empty, determine the number of nodes at the current level.
  4. For each node at the current level, dequeue the node. If it is the first node in this level, record its value.
  5. Enqueue the left and right children of the node, if they exist.
  6. Repeat until all levels are processed. The recorded values form the left view of the tree.

Left View of a Binary Tree - Code Examples Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def leftView(root):
    if not root:
        return []
    from collections import deque
    queue = deque([root])
    result = []
    while queue:
        level_size = len(queue)
        for i in range(level_size):
            node = queue.popleft()
            if i == 0:
                result.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    return result

if __name__ == '__main__':
    # Construct binary tree:
    #         1
    #       /   \
    #      2     3
    #     / \     \
    #    4   5     6
    root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6)))
    print(leftView(root))