Skip to content

Commit d94d226

Browse files
committedJan 24, 2022
adding a method to get the successor of a node inside the birany search tree data structure
1 parent 196afdc commit d94d226

File tree

3 files changed

+9776
-2703
lines changed

3 files changed

+9776
-2703
lines changed
 

‎package-lock.json

+9,740-2,703
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js

+19
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,23 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
148148

149149
return this.left.findMin();
150150
}
151+
152+
/**
153+
* @return {BinarySearchTreeNode}
154+
*/
155+
successor() {
156+
if (this.right) {
157+
return this.right.findMin();
158+
}
159+
160+
let currentNode = this;
161+
let { parent } = currentNode;
162+
163+
while (parent !== null && parent.right && parent.right.value === currentNode.value) {
164+
currentNode = parent;
165+
parent = currentNode.parent;
166+
}
167+
168+
return parent;
169+
}
151170
}

‎src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -252,4 +252,21 @@ describe('BinarySearchTreeNode', () => {
252252

253253
expect(childNode.parent).toBeNull();
254254
});
255+
256+
it('should get the successor of a node', () => {
257+
const rootNode = new BinarySearchTreeNode(5);
258+
rootNode.insert(2);
259+
rootNode.insert(3);
260+
rootNode.insert(1);
261+
rootNode.insert(7);
262+
rootNode.insert(6);
263+
264+
const node = rootNode.find(1);
265+
const node2 = rootNode.find(6);
266+
const node3 = rootNode.find(7);
267+
268+
expect(node.successor().value).toBe(2);
269+
expect(node2.successor().value).toBe(7);
270+
expect(node3.successor()).toBeNull();
271+
});
255272
});

0 commit comments

Comments
 (0)
Please sign in to comment.