Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8140630

Browse files
Completed BST lookup method (#7 IP)
1 parent ab34b07 commit 8140630

File tree

1 file changed

+39
-5
lines changed

1 file changed

+39
-5
lines changed

‎Data-Structures/Trees/BinarySearchTree.ts

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ export default class BinarySearchTree {
1313
}
1414

1515
public insert(value: number) {
16-
// TODO: Insert value into BST
17-
1816
// If empty tree, create root
1917
if(this.root === null) {
2018
this.root = new BNode(value);
@@ -50,8 +48,35 @@ export default class BinarySearchTree {
5048
}
5149

5250
public lookup(value: number) {
53-
// TODO: Find value in BST
54-
console.log("Lookup not implemented");
51+
let currentNode: BNode;
52+
53+
if(!!this.root) {
54+
currentNode = this.root;
55+
} else {
56+
return null;
57+
}
58+
59+
while(true) {
60+
// We found our value!
61+
if (value === currentNode.getValue()) {
62+
return currentNode;
63+
}
64+
65+
66+
if (value < currentNode.getValue()) { // Value is smaller than current node
67+
if(!!currentNode.getLeft()) { // If left child exists
68+
currentNode = currentNode.getLeft(); // Move into left child
69+
continue;
70+
}
71+
return null; // No left child, value DNE
72+
} else { // Value is greater than current node
73+
if(!!currentNode.getRight()) { // If right child exists
74+
currentNode = currentNode.getRight(); // Move into right child
75+
continue;
76+
}
77+
return null; // No right child, value DNE
78+
}
79+
}
5580
}
5681

5782
public remove(value: number) {
@@ -88,7 +113,16 @@ if (import.meta.main) {
88113
tree.insert(170);
89114
tree.insert(15);
90115
tree.insert(1);
91-
console.log(JSON.stringify(traverseFrom(tree.getRoot())));
116+
console.log('Tree: ', JSON.stringify(traverseFrom(tree.getRoot())));
117+
printNode(tree, 4);
118+
printNode(tree, 17);
119+
printNode(tree, 40);
120+
printNode(tree, 170);
92121

93122
// RUN: deno run Data-Structures/Trees/BinarySearchTree.ts
123+
}
124+
125+
function printNode(tree: BinarySearchTree, value: number): void {
126+
const requestedNode = tree.lookup(value);
127+
console.log('Find', value + ':', !!requestedNode ? JSON.stringify(requestedNode) : 'Node not found.');
94128
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /