fix: Ignore inserting the duplicate into RedBlackTree. refactor: renamed the helpers to common

This commit is contained in:
Revone 2023-11-20 16:15:49 +08:00
parent d3a6bdac25
commit 5eaf1d6aab
5 changed files with 28 additions and 6 deletions

View file

@ -1727,7 +1727,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
/**
* The `print` function is used to display a binary tree structure in a visually appealing way.
* @param {N | null | undefined} root - The `root` parameter is of type `BTNKey | N | null |
* @param {N | null | undefined} beginRoot - The `root` parameter is of type `BTNKey | N | null |
* undefined`. It represents the root node of a binary tree. The root node can have one of the
* following types:
*/

View file

@ -103,11 +103,16 @@ export class RedBlackTree<V = any, N extends RedBlackTreeNode<V, N> = RedBlackTr
while (x !== this.NIL) {
y = x;
if (x && node.key < x.key) {
x = x.left;
} else {
x = x?.right;
if (x) {
if (node.key < x.key) {
x = x.left;
} else if (node.key > x.key){
x = x?.right;
} else {
return;
}
}
}
node.parent = y;

View file

@ -1,3 +1,3 @@
export * from './data-structures';
export * from './helpers';
export * from './common';
export * from './utils';

View file

@ -487,4 +487,21 @@ describe('RedBlackTree', () => {
}
isDebug && console.log(performance.now() - cS);
});
it('duplicates', () => {
tree.addMany([9,8,7,8,8,8,2,3,6,5,5,4]);
tree.print();
expect(tree.size).toBe(8);
expect(tree.isBST()).toBe(true);
expect(tree.isAVLBalanced()).toBe(true);
tree.addMany([10, 5, 2, 11]);
expect(tree.size).toBe(10);
expect(tree.isBST()).toBe(true);
expect(tree.isAVLBalanced()).toBe(true);
tree.clear();
tree.addMany([10, 20, 30, 40, 50, 60])
expect(tree.isAVLBalanced()).toBe(false);
})
});