Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created July 6, 2025 07:04
Show Gist options
  • Save gbajaj/1211f5b7222fbdc05d6925b5fd247e05 to your computer and use it in GitHub Desktop.
Save gbajaj/1211f5b7222fbdc05d6925b5fd247e05 to your computer and use it in GitHub Desktop.
Traverses and collects node values in a BFS Tree Traversal
class Solution {
fun levelOrder(root: TreeNode?): List<List<Int>> {
val twoDList = mutableListOf<MutableList<Int>>()
levelOrderRecursive(root, twoDList, 0)
return twoDList
}
fun levelOrderRecursive(root: TreeNode?, list: MutableList<MutableList<Int>>, level: Int) {
if (root == null) return
// Since we might not have a list existing at that level, lets add if needed
if (list.size == level) list.add(mutableListOf<Int>())
list[level].add(root.`val`)
levelOrderRecursive(root.left, list, level + 1)
levelOrderRecursive(root.right, list, level + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment