Skip to main content

Breadth First Search

This technique uses recursion or iterative approach using queue to traverse of a tree in a level-by-level order. A queue keeps track of all the nodes of a level before jumping onto the next level.

How to Identify

  • Data Structure Involves: Tree, Graph
  • Question Type: Traverse a tree in a level-by-level order.

Example

Binary Tree Level Order Traversal

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).

Tree

Example
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
levelOrder.ts
import {TreeNode} from "./TreeNode"
function levelOrder(root: TreeNode | null): number[][] {
const levels: number[][] = []

function helper(root: TreeNode | null, level: number) {
if(root === null) return
if(levels.length === level) levels[level] = []

levels[level].push(root.val)
helper(root.left, level+1)
helper(root.right, level+1)
}

helper(root, 0)
return levels
}
ProblemsDifficulty
1Binary Tree Level Order TraversalMedium
2Binary Tree Zigzag Level Order TraversalMedium