Build a BinaryTree class — a hierarchical data structure where every node holds a value and has at most two children, left and right. You'll implement level-order insertion, value search, and the three classic depth-first traversals (inorder, preorder, postorder). This is not a binary search tree — there's no ordering rule between parent and child, just the shape constraint of at most two children per node. See MDN's tree traversal overview for the broader concept.
class BinaryTree {
constructor() // starts with root = null
insert(value): void // level-order: fill the shallowest empty slot, leftmost first
search(value): boolean // true if any node holds this value
inorder(): Array<any> // left, node, right — values in visit order
preorder(): Array<any> // node, left, right
postorder(): Array<any> // left, right, node
}
Each internal node has the shape { val, left, right } where left and right are either another node or null.
const t = new BinaryTree();
t.insert(1); t.insert(2); t.insert(3); t.insert(4); t.insert(5);
// 1
// / \
// 2 3
// / \
// 4 5
t.preorder(); // [1, 2, 4, 5, 3]
t.inorder(); // [4, 2, 5, 1, 3]
t.postorder(); // [4, 5, 2, 3, 1]
t.search(5); // true
t.search(99); // false
const empty = new BinaryTree();
empty.inorder(); // []
empty.search(1); // false
insert becomes the root; the next two fill its left then right; the next four fill the grandchildren left-to-right.value < parent → go left rule. Duplicates are allowed; they just take the next free slot.[]; search returns false.