compare by node.val
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BST {
constructor() {
this.root = null;
}
// create new Node
insert(val) {
const newNode = new TreeNode(val);
if (!this.root) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
insertNode(root, newNode) {
// newNode is smaller than root
if (newNode.val < root.val) {
// when root.left not exists, newNode be the left node of root
if (!root.left) {
root.left = newNode;
}
// otherwise compare root.left node and newNode again
else {
root.left = this.insertNode(root.left, newNode);
}
}
// newNode is bigger than root
else {
if (!root.right) {
root.right = newNode;
} else {
root.right = this.insertNode(root.right, newNode);
}
}
return root; //
}
traverse(tree) {
if (tree) {
this.traverse(tree.left);
console.log(tree.val);
this.traverse(tree.right);
} else {
console.log(null);
}
}
remove() {}
}
const bst = new BST();
bst.insert(3);
bst.insert(9);
bst.insert(8);
bst.insert(2);
console.log(bst);