Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Created June 2, 2022 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/85474b0fe2090c069cc6fc2e102ad205 to your computer and use it in GitHub Desktop.
Save MorrisLaw/85474b0fe2090c069cc6fc2e102ad205 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal - LeetCode 102
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return nil
}
q := []*TreeNode{root}
var result [][]int
for len(q) != 0 {
size := len(q)
var currLvl []int
for i := 0; i < size; i++ {
curr := q[len(q)-1]
if len(q) != 0 {
q = q[:len(q)-1]
}
currLvl = append(currLvl, curr.Val)
if curr.Left != nil {
q = append([]*TreeNode{curr.Left}, q...)
}
if curr.Right != nil {
q = append([]*TreeNode{curr.Right}, q...)
}
}
result = append(result, currLvl)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment