Merge pull request #11 from zrwusa/binarytree

[binarytree] modified the getDepth method to adhere to the proper def…
This commit is contained in:
zrwusa 2023-10-18 18:29:31 +08:00 committed by GitHub
commit f903804b0b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 5 deletions

View file

@ -350,16 +350,20 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
/**
* The function calculates the depth of a node in a binary tree.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter can be one of the following:
* @param {N | BinaryTreeNodeKey | null} distNode - The `distNode` parameter can be any node of the tree
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter can be the predecessor node of distNode
* @returns the depth of the given node or binary tree.
*/
getDepth(beginRoot: N | BinaryTreeNodeKey | null = this.root): number {
getDepth(distNode: N | BinaryTreeNodeKey | null, beginRoot: N | BinaryTreeNodeKey | null = this.root): number {
if (typeof distNode === 'number') distNode = this.get(distNode, 'key');
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot, 'key');
let depth = 0;
while (beginRoot?.parent) {
while (distNode?.parent) {
if (distNode === beginRoot) {
return depth;
}
depth++;
beginRoot = beginRoot.parent;
distNode = distNode.parent;
}
return depth;
}

View file

@ -105,6 +105,19 @@ describe('BinaryTree', () => {
expect(binaryTree.has(4)).toBe(false);
});
test('should getDepth return correct depth', () => {
binaryTree.add(1);
expect(binaryTree.getDepth(1)).toBe(0);
binaryTree.add(2);
expect(binaryTree.getDepth(2)).toBe(1);
binaryTree.add(3);
expect(binaryTree.getDepth(3, 1)).toBe(1);
binaryTree.add(4);
expect(binaryTree.getDepth(4, 1)).toBe(2);
expect(binaryTree.getDepth(4)).toBe(2);
expect(binaryTree.getDepth(4, 2)).toBe(1);
});
test('should traverse in-order', () => {
binaryTree.add(4);
binaryTree.add(2);