Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 18, 2021 01:55
Show Gist options
  • Save CarlaTeo/bd4ea4173d434a542996ec89701ef166 to your computer and use it in GitHub Desktop.
Save CarlaTeo/bd4ea4173d434a542996ec89701ef166 to your computer and use it in GitHub Desktop.
[JS ] Binary Search Tree iterator to find the next smallest number
class BSTIterator {
constructor(root) {
this.nextValue = null;
this.sortedValues = getInOrderValues(root);
}
hasNext() {
if(!this.nextValue) {
const next = this.sortedValues.next();
this.nextValue = next.done ? null : next.value;
}
return this.nextValue !== null;
}
next() {
if(this.hasNext()) {
const aux = this.nextValue;
this.nextValue = null;
return aux;
}
return null;
}
}
function* getInOrderValues(root) {
if(root) {
if(root.left) {
yield * getInOrderValues(root.left);
}
yield root.data;
if(root.right) {
yield * getInOrderValues(root.right);
}
}
}
// ---------------------------------- Test ---------------------------------//
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
const root = new Node(7);
const node5 = new Node(5);
const node20 = new Node(20);
const node18 = new Node(18);
const node25 = new Node(25);
root.left = node5;
root.right = node20;
node20.left = node18;
node20.right = node25;
// 7
// / \
// 5 20
// / \
// 18 25
const iterator = new BSTIterator(root);
console.log(iterator.next()); // 5
console.log(iterator.next()); // 7
console.log(iterator.hasNext()); // true
console.log(iterator.next()); // 18
console.log(iterator.hasNext()); // true
console.log(iterator.next()); // 20
console.log(iterator.hasNext()); // true
console.log(iterator.next()); // 25
console.log(iterator.hasNext()); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment