Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RJ-software-outsourcing/a1de14fcd32f8ad4771341672be90566 to your computer and use it in GitHub Desktop.
Save RJ-software-outsourcing/a1de14fcd32f8ad4771341672be90566 to your computer and use it in GitHub Desktop.
class Node {
constructor(value) {
this.value = value;
}
insert(insertedValue) {
if (insertedValue > this.value) {
if (this.right) {
this.right.insert(insertedValue);
} else {
this.right = new Node(insertedValue);
if (this.left) {
const leftNext = this.left.next;
this.left.next = this.right;
this.right.next = leftNext;
} else {
const currentNext = this.next;
this.next = this.right;
this.right.next = currentNext;
}
}
} else if (insertedValue < this.value) {
if (this.left) {
this.left.insert(insertedValue);
} else {
this.left = new Node(insertedValue);
const currentNext = this.next;
this.left.next = currentNext;
this.next = this.left;
}
}
}
}
const MAX = 20;
function getRandomInt() {
return Math.floor(Math.random() * Math.floor(MAX));
}
function traverse(node) {
if (node) {
console.log(node.value);
traverse(node.left);
traverse(node.right);
}
}
function goNext(node) {
if (node) {
console.log(node.value);
return node.next;
}
}
const root = new Node(getRandomInt());
for (let i = 0; i < (MAX / 2); i++) {
root.insert(i);
root.insert(MAX - i);
}
traverse(root);
console.log('-----------');
// console.log(root.value);
const rec = {};
let tmp = root.next;
let count = 0;
console.log(count, root.value);
function go() {
if (tmp) {
count++;
if (rec[tmp.value]) {
throw new Error('duplicated!');
} else {
rec[tmp.value] = true;
console.log(count, tmp.value);
tmp = tmp.next;
setTimeout(go, 500);
}
}
}
go();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment