Created
June 2, 2022 11:26
-
-
Save MorrisLaw/85474b0fe2090c069cc6fc2e102ad205 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal - LeetCode 102
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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