Data Structures: Use Breadth First Search in a Binary Search Tree - toying with es6

Tell us what’s happening:

the instruction inside the recursive call of ‘visit’ are building the list of next nodes to visit. Is there a more concise way to addIfNotNull to an array than filter it afterward ?

Your code so far


function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
this.levelOrder = function () {
  const visit = (cur) => [
    ...cur.map(node => node.value),
    ...(cur.length === 0)? []: visit(cur.flatMap(node =>
         [node.left, node.right]).filter(x => x!=null))
  ];
  return (this.root)? visit([this.root]): null;
}
this.reverseLevelOrder = function () {
  const visit = (cur) => [
    ...cur.map(node => node.value).reverse(), 
    ...(cur.length === 0)? []: visit(cur.flatMap(node =>
         [node.left, node.right]).filter(x => x!=null))
  ];
  return (this.root)? visit([this.root]): null;
}
// change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36.

Challenge: Use Breadth First Search in a Binary Search Tree

Link to the challenge:
https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-breadth-first-search-in-a-binary-search-tree

1 Like

this.reverseLevelOrder = function () {
const visit = (cur) => [
…cur.map(node => node.value).reverse(),
…(cur.length === 0)? : visit(cur.flatMap(node =>
[node.left, node.right]).filter(x => x!=null))
];
return (this.root)? visit([this.root]): null;
}
// change code Sarkari Result 192.168.1.1 above this line
}