Last active
November 10, 2020 22:39
-
-
Save HallexCosta/839f0e85ded58fff91d1bfe7f01d9a3b to your computer and use it in GitHub Desktop.
Example of binary tree search data structure with TypeScript
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
type DataStructure = { | |
value: number | |
branchRight: DataStructure | |
branchLeft: DataStructure | |
} | |
class Tree { | |
private static data: DataStructure | |
constructor() { | |
Tree.data = {} as DataStructure | |
} | |
add(value: number): void { | |
this.addOnBranch(Tree.data, value) | |
} | |
addOnBranch(branch: DataStructure, value: number): void { | |
if (branch.value) { | |
if (value > branch.value) { | |
this.addOnBranch(branch.branchRight, value) | |
} else { | |
this.addOnBranch(branch.branchLeft, value) | |
} | |
} else { | |
branch.value = value | |
branch.branchRight = {} as DataStructure | |
branch.branchLeft = {} as DataStructure | |
} | |
} | |
getData(): DataStructure { | |
return Tree.data | |
} | |
} | |
const tree = new Tree() | |
tree.add(10) | |
tree.add(9) | |
tree.add(11) | |
tree.add(12) | |
console.log("Tree Inserted #4", tree.getData()) | |
/* | |
OUTPUT: | |
Tree Inserted #4 { | |
value: 10, | |
branchRight: { | |
value: 11, | |
branchRight: { | |
value: 12, | |
branchRight: {}, | |
branchLeft: {} | |
}, | |
branchLeft: {} | |
}, | |
branchLeft: { | |
value: 9, | |
branchRight: {}, | |
branchLeft: {} | |
} | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment