LeetCode - Blind 75 - Binary Tree Level Order Traversal

The Problem Given the root of a binary tree, return the level order traversal of its nodes’ values (i.e., from left to right, level by level). Examples Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Input: root = [1] Output: [[1]] Input: root = [] Output: [] Constraints The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000 BFS Solution func levelOrder(_ root: TreeNode?) -> [[Int]] { if root == nil { return [] } var queue: [TreeNode?] = [] queue.append(root) var res: [[Int]] = [] while !queue.isEmpty { var level: [Int] = [] for _ in 0 ..< queue.count { let node = queue.removeFirst() if let node = node { level.append(node.val) queue.append(node.left) queue.append(node.right) } } if !level.isEmpty { res.append(level) } } return res } Explanation When you see that a binary tree problem involves level order traversal, it means the solution usually implies the breadth-first search (BFS) algorithm. BFS is a common solution to this problem because, according to Wikipedia, breadth-first search is also called “level-order search.” The core idea behind BFS is to iterate level by level from top to bottom, and from left to right. ...

January 8, 2025 · 2 min · Dmytro Chumakov