Programming & Development / April 8, 2025

LeetCode 102: Binary Tree Level Order Traversal in Go – Solution with BFS Approach

Go Golang LeetCode Binary Tree Level Order Traversal BFS Queue Tree Traversal Algorithm Binary Tree Traversal Breadth-First Search

Introduction

LeetCode 102: Binary Tree Level Order Traversal is a problem that asks you to return the level order traversal of a binary tree’s nodes, from top to bottom, level by level. This is a classic tree traversal problem where you must visit each node of the tree level by level, from left to right.

In this problem, you will implement an algorithm that performs Breadth-First Search (BFS) on a binary tree, where nodes are visited level by level.

Problem Statement

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example:

go

Input: 
    [3, 9, 20, null, null, 15, 7]
Output: 
    [
      [3],
      [9, 20],
      [15, 7]
    ]

Input:
    [1]
Output:
    [
      [1]
    ]

Input:
    []
Output:
    []

Approach:

Breadth-First Search (BFS) Approach

The problem is best solved using Breadth-First Search (BFS). BFS explores all nodes at the present depth level before moving on to nodes at the next depth level. It is commonly implemented using a queue, where we first enqueue the root node and then explore its left and right children in a level-wise manner.

Steps:

  1. Base Case: If the root is nil, return an empty list (i.e., the tree is empty).
  2. Use a Queue: Initialize a queue to store nodes at each level. Start with the root node.
  3. Level-wise Processing: Process the nodes level by level:
  • For each level, traverse all nodes in the queue.
  • For each node, add its value to the current level's result list.
  • Enqueue the left and right children of each node.
  1. Repeat Until the Queue is Empty: Continue processing until all levels have been traversed.

Go Implementation

BFS Solution with Queue

go

package main

// TreeNode represents the structure of a binary tree node.
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

// levelOrder performs level order traversal of a binary tree.
func levelOrder(root *TreeNode) [][]int {
    // If the tree is empty, return an empty slice.
    if root == nil {
        return [][]int{}
    }
    
    var result [][]int
    queue := []*TreeNode{root}

    // Perform BFS using a queue.
    for len(queue) > 0 {
        levelSize := len(queue)
        var levelValues []int
        
        // Process all nodes at the current level.
        for i := 0; i < levelSize; i++ {
            node := queue[0]
            queue = queue[1:] // Dequeue
            
            // Add the node's value to the level result.
            levelValues = append(levelValues, node.Val)
            
            // Enqueue left and right children, if they exist.
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        
        // Add the current level values to the result.
        result = append(result, levelValues)
    }

    return result
}

Explanation:

  1. TreeNode Structure:
  • The TreeNode structure represents a node in a binary tree, with three fields: Val (the value of the node), Left (pointer to the left child), and Right (pointer to the right child).
  1. levelOrder Function:
  • This function takes the root of the binary tree and returns a 2D slice containing the level order traversal of the tree's nodes.
  1. Queue for BFS:
  • The function uses a queue to process nodes level by level. Initially, the queue contains only the root node.
  • For each level, the function processes each node in the queue by dequeuing it, adding its value to the current level’s result, and enqueuing its left and right children.
  1. Level-wise Processing:
  • For each level, a new slice (levelValues) is used to store the node values at that level.
  • After processing all nodes at the current level, the function appends levelValues to the final result (result).

Time and Space Complexity

MetricComplexityTime ComplexityO(n)Space ComplexityO(n)

Where:

  • n is the number of nodes in the binary tree.

Time Complexity:

  • We visit each node exactly once, so the time complexity is O(n), where n is the number of nodes in the tree.

Space Complexity:

  • The space complexity is determined by the queue used for BFS. In the worst case (a fully balanced tree), the maximum number of nodes at any level is O(n/2), which simplifies to O(n).
  • Therefore, the space complexity is O(n).

Edge Cases

  1. Empty Tree:
  • Input: root = nil
  • Output: []
  • Explanation: An empty tree has no nodes, so the output is an empty list.
  1. Single Node Tree:
  • Input: root = [1]
  • Output: [[1]]
  • Explanation: A tree with only one node will have just one level.
  1. Tree with Multiple Levels:
  • Input: root = [3, 9, 20, nil, nil, 15, 7]
  • Output: [[3], [9, 20], [15, 7]]
  • Explanation: The tree has three levels, and the output shows the nodes at each level.
  1. Right-skewed Tree:
  • Input: root = [1, null, 2, null, 3]
  • Output: [[1], [2], [3]]
  • Explanation: A right-skewed tree where each node has only a right child.
  1. Left-skewed Tree:
  • Input: root = [1, 2, null, 3]
  • Output: [[1], [2], [3]]
  • Explanation: A left-skewed tree where each node has only a left child.

Conclusion

LeetCode 102: Binary Tree Level Order Traversal is a problem that tests your understanding of tree traversal techniques. The Breadth-First Search (BFS) approach provides an efficient solution by processing nodes level by level, using a queue to keep track of nodes at each level. The solution has a time complexity of O(n) and a space complexity of O(n), making it optimal for large trees. This approach is widely applicable for many tree-related problems that involve level-wise processing or comparison.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex