A binary search tree that stays sorted
A binary search tree keeps every value smaller than a node in its left subtree and every larger value in its right, so an in-order walk emerges sorted and a lookup only ever follows one path down.
Implement a BST class holding numbers. It is constructed with no arguments and starts empty. insert(value) adds a number and returns true, or returns false and changes nothing if that number is already in the tree. has(value) returns true or false. inOrder() returns an array of the stored numbers in ascending order, and [] when empty. size() returns how many distinct numbers are stored. min() and max() return the smallest and largest stored numbers, or undefined when the tree is empty.
Examples
const t = new BST();
[8, 3, 10, 1, 6, 14].forEach((v) => t.insert(v));
t.inOrder(); // [1, 3, 6, 8, 10, 14]
t.min(); // 1
t.max(); // 14Insert in any order; an in-order walk comes out sorted.
const t = new BST();
t.insert(5); // true
t.insert(5); // false — duplicate
t.has(5); // true
t.has(99); // falseWhat it has to do
inOrder()returns the values in ascending order.insertreturnsfalsefor a duplicate and does not add it twice.hasreturnsfalsefor a value that was never inserted.min()andmax()returnundefinedon an empty tree.size()counts distinct values only.
Notes
- On a balanced tree,
insert,has,minandmaxare O(log n). On a pathological insertion order (already-sorted input) the tree degenerates to a linked list and every operation becomes O(n). - In-order means left subtree, then the node, then the right subtree — the recipe that produces ascending output on any BST.
min()is just as-far-left-as-possible;max()is the mirror. Both skip the recursion entirely.
Stuck? The javascript course covers everything this challenge needs.
- 1.reads back in ascending order regardless of insert order
- 2.rejects duplicates
- 3.finds and misses values
- 4.an empty tree reports nothing
- 5.reports the extremes
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.