Binary TreeLoading saved progress…

Binary Tree

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.

Signature

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.

Examples

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

Notes

  • Level-order insertion — fill the tree row by row, leftmost empty slot first. The first insert becomes the root; the next two fill its left then right; the next four fill the grandchildren left-to-right.
  • Not a BST — there is no value < parent → go left rule. Duplicates are allowed; they just take the next free slot.
  • Traversals return arrays — return a new array of values in visit order. Do not mutate the tree.
  • Empty tree is valid — all three traversals on an empty tree return []; search returns false.
  • Out of scope — deletion, balancing, parent pointers, serialization. Just the six methods above.
Loading editor…