AniUI Academy

A binary search tree that stays sorted

mediumData Structures+250 XPPractice

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();      // 14

Insert 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);    // false

What it has to do

  • inOrder() returns the values in ascending order.
  • insert returns false for a duplicate and does not add it twice.
  • has returns false for a value that was never inserted.
  • min() and max() return undefined on an empty tree.
  • size() counts distinct values only.

Notes

  • On a balanced tree, insert, has, min and max are 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.