Perform Level Order Traversal on a Binary Tree Using Go

This program demonstrates how to perform a level order traversal of a binary tree. Level order traversal involves visiting all nodes at each depth level from left to right before moving to the next level.

Program Explanation

The approach uses a queue to keep track of nodes to be processed, ensuring that nodes are processed in the correct order of their depth levels. Each node is visited and its children are added to the queue, thus maintaining the order of traversal.

Code Structure

  1. TreeNode struct: Defines the structure of the binary tree nodes.
  2. levelOrder function: Implements the level order traversal and returns a slice of slices containing node values at each level.

Code with Documentation

package main

import (
    "fmt"
)

// TreeNode defines a binary tree node.
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

// levelOrder performs level order traversal of the binary tree.
func levelOrder(root *TreeNode) [][]int {
    if root == nil {
        return nil
    }
    
    var result [][]int
    queue := []*TreeNode{root}
    
    for len(queue) > 0 {
        levelSize := len(queue)
        currentLevel := make([]int, levelSize)
        
        for i := 0; i < levelSize; i++ {
            current := queue[0]
            queue = queue[1:]
            currentLevel[i] = current.Val
            
            if current.Left != nil {
                queue = append(queue, current.Left)
            }
            if current.Right != nil {
                queue = append(queue, current.Right)
            }
        }
        result = append(result, currentLevel)
    }
    
    return result
}

func main() {
    // Construct a simple binary tree:
    //        1
    //       / \
    //      2   3
    //     / \   \
    //    4   5   6
    root := &TreeNode{1, &TreeNode{2, &TreeNode{4, nil, nil}, &TreeNode{5, nil, nil}}, &TreeNode{3, nil, &TreeNode{6, nil, nil}}}

    levels := levelOrder(root)
    fmt.Println("Level order traversal of the binary tree:")
    for _, level := range levels {
        fmt.Println(level)
    }
}

Conclusion

The Go code effectively demonstrates a level order traversal of a binary tree, using a queue-based approach to ensure that all nodes are visited in their level-wise sequence. This traversal method is crucial for many tree operations and is commonly used in algorithms such as breadth-first search (BFS).

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)