Buggy BST Insert
Spot the subtle recursion bug that silently drops nodes in a binary search tree insert.
Codejavascript
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Unlike a heap-backed priority queue (which only tracks min/max),
// a BST keeps ALL keys ordered so we can do lookups by value.
function insert(root, val) {
if (root === null) return new Node(val);
if (val < root.val) {
insert(root.left, val);
} else {
insert(root.right, val);
}
return root;
}
let tree = null;
tree = insert(tree, 50);
insert(tree, 30);
insert(tree, 70);
insert(tree, 20);
// Expected in-order: 20, 30, 50, 70What is the bug that causes inserted values (20, 30, 70) to be lost?