Binary Tree Level Order Traversal

Problem statement

Walk the tree level by level (left to right within a level) and return a list of levels, each level being the node values on that depth.

Example:

Input:

root = [3, 9, 20, null, null, 15, 7]

Expected output:

[[3], [9, 20], [15, 7]]

Practice on LeetCode: Binary Tree Level Order Traversal

Golang Solution

BFS with a queue. For each level, process exactly the nodes currently in the queue (levelSize), collect their values, and enqueue their children for the next level.

Time: O(n) — each node visited once
Space: O(n) — queue can hold up to a full level of nodes

func levelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    result := [][]int{}
    queue := []*TreeNode{root}

    for len(queue) > 0 {

        levelSize := len(queue)
        level := []int{}

        for i := 0; i < levelSize; i++ {

            node := queue[0]
            queue = queue[1:]

            level = append(level, node.Val)

            if node.Left != nil {
                queue = append(queue, node.Left)
            }

            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }

        result = append(result, level)
    }

    return result
}