Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

Tree BFS (Breath-first-search) in javascript

✨ Iterative Algorithm

const bfs = (root) => {
  const queue = [root];
  let res = 0;

  while (queue.length) {
    const len = queue.length;

    for (let i = 0; i < len; i += 1) {
      const cur = queue.shift();

      // do logic

      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
};

return bfs(root);