Last active
November 10, 2020 22:40
-
-
Save HallexCosta/d32edf348b8e74c4584360608d5f5b27 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 BranchDataStructure = { | |
right: TreeDataStructure | |
left: TreeDataStructure | |
} | |
type TreeDataStructure = { | |
value: number | |
branch: BranchDataStructure | |
} | |
interface TreeInterface { | |
add(value: number): void | |
getData(): TreeDataStructure | |
} | |
class Branch { | |
public right: TreeDataStructure = {} as TreeDataStructure | |
public left: TreeDataStructure = {} as TreeDataStructure | |
} | |
class Tree implements TreeInterface { | |
private static data: TreeDataStructure = {} as TreeDataStructure | |
public constructor() { | |
Tree.data.branch = new Branch | |
} | |
public add(value: number): void { | |
this.addOnBranch(Tree.data, value) | |
} | |
private addOnBranch(tree: TreeDataStructure, value: number): void { | |
if (tree.value) { | |
if (value > tree.value) { | |
this.addOnBranch(tree.branch.right, value) | |
} else { | |
this.addOnBranch(tree.branch.left, value) | |
} | |
} else { | |
tree.value = value | |
tree.branch = new Branch | |
} | |
} | |
public getData(): TreeDataStructure { | |
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", { | |
"branch": { | |
"right": { | |
"value": 11, | |
"branch": { | |
"right": { | |
"value": 12, | |
"branch": { | |
"right": {}, | |
"left": {} | |
} | |
}, | |
"left": {} | |
} | |
}, | |
"left": { | |
"value": 9, | |
"branch": { | |
"right": {}, | |
"left": {} | |
} | |
} | |
}, | |
"value": 10 | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment