LeetCode 102. Binary Tree Level Order Traversal

LeetCode Notes [51]: Kotlin solution with a queue used

John Lu
Mar 13, 2023
© MAGNIFIER / iStock / Getty Images

Problem

Implementation

class Solution {
fun levelOrder(root: TreeNode?): List<List<Int>> {
val result = mutableListOf<List<Int>>()
val queue: Queue<TreeNode> = LinkedList()
root?.let { queue.add(it) }
while (queue.isNotEmpty()) {
val level = mutableListOf<Int>()
for (i in 0 until queue.size) {
val node = queue.poll()
level.add(node.`val`)
node.left?.let { queue.add(it) }
node.right?.let { queue.add(it) }
}
result.add(level)
}
return result
}
}

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

--

--

John Lu

Android Developer. Deeply motivated by challenges and tends to be excited by breaking conventional ways of thinking and doing. He builds fun and creative apps.