179 words
1 minutes
Implementing Level Order Traversal of a Binary Tree in Go
Level order traversal is a common algorithm used to traverse a binary tree level by level. Let’s see my the code.
TreeNode Structure
The TreeNode struct
represents a node in a binary tree. Each node contains a value (Val
), a pointer to the left child (Left
), and a pointer to the right child (Right
).
package DSA
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
Level Order Traversal Function
The levelOrder
function performs a level order traversal on a binary tree and returns the values of the nodes in a 2D
slice, where each inner slice represents a level of the tree.
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue := []*TreeNode{root}
output := [][]int{}
for len(queue) != 0 {
levelSize := len(queue)
var level []int
for i := 0; i < levelSize; i++ {
currentNode := queue[0]
queue = queue[1:]
level = append(level, currentNode.Val)
if currentNode.Left != nil {
queue = append(queue, currentNode.Left)
}
if currentNode.Right != nil {
queue = append(queue, currentNode.Right)
}
}
output = append(output, level)
}
return output
}
Implementing Level Order Traversal of a Binary Tree in Go
https://rabisiddique.com/posts/level-order-traversal-go/Author
Rabi Siddique
Published at
2024-02-13