Programming & Development / April 8, 2025

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

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

Introduction

LeetCode 103: Binary Tree Zigzag Level Order Traversal is a problem that asks you to return the zigzag level order traversal of a binary tree’s nodes. This means that you need to traverse the tree level by level, but the direction of traversal alternates between left-to-right and right-to-left at each level.

This problem is similar to LeetCode 102: Binary Tree Level Order Traversal, but it requires an additional step of reversing the direction at each level. The algorithm can be implemented efficiently using Breadth-First Search (BFS) with a slight modification to alternate the direction at each level.

Problem Statement

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level, and alternates between them).

Example:

go

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

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

Input:
    []
Output:
    []

Approach:

Breadth-First Search (BFS) with Alternating Direction

We can use Breadth-First Search (BFS) to traverse the tree level by level, but with an added complexity of reversing the direction at each level.

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: For each level, we alternate the direction of traversal:
  • If the level is even (starting from 0), process the nodes left to right.
  • If the level is odd, process the nodes right to left.
  1. Enqueue Children: Enqueue the left and right children of each node for future processing.
  2. Repeat Until the Queue is Empty: Continue processing until all levels have been traversed.

Go Implementation

BFS Solution with Zigzag Traversal

go

package main

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

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

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

    // 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)
            }
        }

        // Reverse the level's values if we are going right to left.
        if !leftToRight {
            reverse(levelValues)
        }

        // Add the current level values to the result.
        result = append(result, levelValues)

        // Toggle the direction for the next level.
        leftToRight = !leftToRight
    }

    return result
}

// reverse reverses the order of elements in a slice.
func reverse(nums []int) {
    for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
        nums[i], nums[j] = nums[j], nums[i]
    }
}

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. zigzagLevelOrder Function:
  • This function takes the root of the binary tree and returns a 2D slice containing the zigzag level order traversal of the tree's nodes.
  • The BFS approach is used with a queue to process nodes level by level.
  1. Direction Toggle:
  • The variable leftToRight controls whether the current level should be traversed left to right or right to left. After processing each level, we toggle this flag to alternate the direction.
  1. Reverse Function:
  • The reverse function is used to reverse the values of the current level if the direction is right to left. This ensures that the nodes are processed in the correct zigzag order.

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, and the zigzag order is the same as level order.
  1. Tree with Multiple Levels:
  • Input: root = [3, 9, 20, null, null, 15, 7]
  • Output: [[3], [20, 9], [15, 7]]
  • Explanation: The tree has three levels, and the zigzag order alternates directions 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, and the zigzag order is similar to level order.
  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 103: Binary Tree Zigzag Level Order Traversal is a problem that tests your ability to traverse a binary tree in a zigzag (alternating left-to-right and right-to-left) manner. Using a Breadth-First Search (BFS) approach with a queue, you can efficiently solve this problem by toggling the direction of traversal 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 problems that involve traversal with alternating directions or more complex orderings.


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