Explore Library
Code Quiz

Buggy BST Insertion

Find the subtle bug in a recursive binary search tree insertion function.

Codejavascript
class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

function insert(root, value) {
  if (root === null) {
    return new Node(value);
  }
  if (value < root.value) {
    insert(root.left, value);
  } else {
    insert(root.right, value);
  }
  return root;
}

let tree = null;
tree = insert(tree, 10);
insert(tree, 5);
insert(tree, 15);
console.log(tree.left, tree.right); // expected the 5 and 15 nodes

Why does inserting 5 and 15 fail to attach them to the tree?