Skip to content

Breadth First Traverse

Daisho Komiyama edited this page May 31, 2022 · 2 revisions

Write a function that traverses breadth-first then returns an array

      ____ A ____
     /           \
    B             C
   / \           /  \
  D   E         F    G
 /     \       /      \
H       I     J        K

Expected output: [A,B,C,D,E,F,G,H,I,J,K]

const breadthFirstTraverse = (queue, array) => {
  while (queue && queue.length) {
    const node = queue.shift()
    array.push(node.value)
    if (node.left) queue.push(node.left)
    if (node.right) queue.push(node.right)
  }
  
  return array
}

const tree = {
  value: "A",
  left: {
    value: "B",
    left: {
      value: "D",
      left: {
        value: "G",
        left: null,
        right: null,
      },
      right: null,
    },
    right: {
      value: "E",
      left: null,
      right: {
        value: "H",
        left: {
          value: "K",
          left: null,
          right: null,
        },
      },
    },
  },
  right: {
    value: "C",
    left: {
      value: "F",
      left: {
        value: "I",
        left: null,
        right: null,
      },
      right: {
        value: "J",
        left: null,
        right: null,
      },
    },
    right: null,
  },
}

breadthFirstTraverse([tree], []) // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
Clone this wiki locally