Binary Tree Level Order Traversal
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:
Input:
root = [3,9,20,null,null,15,7]
Expected output:
[[3],[9,20],[15,7]]
If you would like to solve the problem on LeetCode, here is the link to the problem: LeetCode problem link
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
}
