Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created July 5, 2025 21:59
Show Gist options
  • Save gbajaj/7b2ae60cd763c530619b9b1c77b1cce7 to your computer and use it in GitHub Desktop.
Save gbajaj/7b2ae60cd763c530619b9b1c77b1cce7 to your computer and use it in GitHub Desktop.
Traverses tree level by level iteratively
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun levelOrder(root: TreeNode?): List<List<Int>> {
val mutableNestedList = mutableListOf<MutableList<Int>>()
if (root == null) return emptyList<List<Int>>()
val q = mutableListOf<TreeNode?>()
// Root node to the Queue
q.add(root)
while (q.isNotEmpty()) {
// For the level out out in Int
val level = mutableListOf<Int>()
// add all child nodes before exhausing entire Queue
val childNodes = mutableListOf<TreeNode>()
while (q.isNotEmpty()) {
val node = q.removeFirst()
// Collection values for the current level for the output
node?.let {level.add(it.`val`)}
// Collect all children nodes for the next level
node?.left?.let {childNodes.add(it)}
node?.right?.let {childNodes.add(it)}
}
// add all nodes for the next level before the next level iteration
q.addAll(childNodes)
// Add to the final out put list
mutableNestedList.add(level)
}
return mutableNestedList
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment