I've written this code for a Binary Search Tree. For the most part I understand how it works when it comes to inserting nodes. What I don't quite get is the while(true) part.
I'm used to comparing some sort of value when using while loops.
For this code, how does it work?
Is it because I'm setting current and the while loop goes back and checks if that matches the value passed? is that how the while loop works with true?
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
}
BinarySearchTree.prototype.insert = function(value) {
const newNode = new Node(value);
if (this.root === null) {
this.root = newNode;
}
let current = this.root;
while(true) {
if (value === current.val) return;
if (value < current.val) {
if (current.left === null) {
current.left = newNode;
}
current = current.left;
} else {
if (current.right === null) {
current.right = newNode;
}
current = current.right;
}
}
}
let tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)
console.log(tree);