Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Created July 13, 2021 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/31286cf7880b72decacc15b8c3c3a367 to your computer and use it in GitHub Desktop.
Save danny-andrews/31286cf7880b72decacc15b8c3c3a367 to your computer and use it in GitHub Desktop.
Binary Tree
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Every value in the Left subtree less than root
// Every value in the right subtree is greater than or equal to the root
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(data) {
var newNode = new Node(data);
if (this.root === null) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
insertNode(node, newNode) {
if (newNode.data < node.data) {
if (node.left === null) {
node.left = newNode;
} else {
this.insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
}
search() {
// Your code here.
}
traverse(fn, node = this.root) {
if (!node) return;
this.traverse(fn, node.left);
fn(node.data);
this.traverse(fn, node.right);
}
print() {
this.traverse(console.log);
}
}
const tree = new BinarySearchTree();
tree.insert(90);
tree.insert(7);
tree.insert(98);
tree.insert(22);
tree.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment