-
-
Save abenteuerzeit/d86e73f01b69662c4ea2690849603f45 to your computer and use it in GitHub Desktop.
Binary Search 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 BinaryTree { | |
constructor(value, depth = 1) { | |
this.value = value; | |
this.depth = depth; | |
this.left = null; | |
this.right = null; | |
} | |
insert(value) { | |
if (value < this.value) { | |
if (!this.left) { | |
this.left = new BinaryTree(value, this.depth + 1); | |
} else { | |
this.left.insert(value); | |
} | |
} else { | |
if (!this.right) { | |
this.right = new BinaryTree(value, this.depth + 1); | |
} else { | |
this.right.insert(value); | |
} | |
} | |
} | |
getNodeByValue(value) { | |
if (this.value === value) { | |
return this; | |
} else if ((this.left) && (value < this.value)) { | |
return this.left.getNodeByValue(value); | |
} else if (this.right) { | |
return this.right.getNodeByValue(value); | |
} else { | |
return null; | |
} | |
} | |
depthFirstTraversal() { | |
if (this.left) { | |
this.left.depthFirstTraversal(); | |
} | |
console.log(`Depth=${this.depth}, Value=${this.value}`); | |
if (this.right) { | |
this.right.depthFirstTraversal(); | |
} | |
} | |
}; | |
module.exports = BinaryTree; |
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
const BinaryTree = require('./BinaryTree'); | |
const randomize = () => Math.floor(Math.random() * 40); | |
const bt = new BinaryTree(15); | |
let numbers = []; | |
for (let i = 0; i < 10; i++) { | |
numbers.push(randomize()); | |
bt.insert(numbers[i]); | |
} | |
console.log(`Inserted [ ${numbers} ] to binary tree`); | |
console.log('Depth First Traversal'); | |
bt.depthFirstTraversal(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment