Created
March 25, 2022 21:28
-
-
Save mustafadalga/d849a98790c634a13e202fa28997e9e1 to your computer and use it in GitHub Desktop.
Binary Search Tree Data Structure Example in Javascript
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(value) { | |
this.value = value; | |
this.left = null; | |
this.right = null; | |
} | |
} | |
class BinarySearchTree { | |
constructor() { | |
this.root = null; | |
} | |
insert(value) { | |
const newNode = new Node(value); | |
if (!this.root) { | |
this.root = newNode; | |
return this; | |
} | |
let current = this.root; | |
while (true) { | |
if (value < current.value) { | |
if (current.left) { | |
current = current.left; | |
} else { | |
current.left = newNode; | |
return this; | |
} | |
} else if (value > current.value) { | |
if (current.right) { | |
current = current.right; | |
} else { | |
current.right = newNode; | |
return this; | |
} | |
} else { | |
return this; | |
} | |
} | |
} | |
find(value) { | |
if (!this.root || !Number.isInteger(value)) return undefined; | |
let current = this.root, found = false; | |
while (current && !found) { | |
if (value < current.value) { | |
current = current.left; | |
} else if (value > current.value) { | |
current = current.right; | |
} else { | |
found = true; | |
} | |
} | |
if (!found) return undefined; | |
return current; | |
} | |
contains(value) { | |
if (!this.root || !Number.isInteger(value)) return false; | |
let current = this.root, found = false; | |
while (current && !found) { | |
if (value < current.value) { | |
current = current.left; | |
} else if (value > current.value) { | |
current = current.right; | |
} else { | |
return true; | |
} | |
} | |
return false; | |
} | |
} | |
const tree = new BinarySearchTree(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment