Created
February 21, 2024 18:54
-
-
Save tdubs42/fd83592f25b862608c149d38edbb3dbc to your computer and use it in GitHub Desktop.
Binary Tree Class - 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 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment