Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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