An interactive visualization of Breadth-First Search on a binary tree. Watch nodes being processed level by level using a queue, building the result array as each level completes.
BFS LeetCode 102 โ Mediumroot of a binary tree, return the level order traversal of its nodes' values
(i.e., from left to right, level by level).null represents a missing node.
Return a list of lists, where each inner list contains the values of nodes at that depth level.
fun levelOrder(root: TreeNode?): List<List<Int>> { if (root == null) { return emptyList() } val result = mutableListOf<List<Int>>() val queue: ArrayDeque<TreeNode> = ArrayDeque() queue.add(root) while (queue.isNotEmpty()) { val levelSize = queue.size val level = mutableListOf<Int>() for (i in 0 until levelSize) { val node = queue.removeFirst() level.add(node.`val`) node.left?.let { queue.add(it) } node.right?.let { queue.add(it) } } result.add(level) } return result}
Level order traversal processes a tree breadth-first โ visiting all nodes at depth 0, then all at depth 1, and so on.
A queue naturally gives us this order: we enqueue children as we process parents.
The trick is tracking where one level ends and the next begins by capturing len(queue) at the start of each level.
level_size = len(queue) โ this is how many nodes are at the current level.level_size nodes from the front of the queue.Every node is enqueued and dequeued exactly once, giving O(n) time. The queue holds at most one full level of the tree at a time โ in a complete binary tree the last level has ~n/2 nodes, so space is O(n).