merge: Bugfix AVLTree comparator (#1084)

The original insertBalance function was doing raw value comparisons as opposed to using the tree's comparator. This is clearly unintentional, and would (ultimately) cause the structure to segfault when constructed with the stringData included in the updated test.

I've added the fix, scanned the rest of the code for similar issues, and added the appropriate test case which passes successfully with the fix. The jest code coverage increases slightly as well with the changes.
This commit is contained in:
k ho k ho?
2022-08-15 09:27:31 -07:00
committed by GitHub
parent 979046897d
commit a133529122
2 changed files with 17 additions and 5 deletions

View File

@ -90,14 +90,14 @@ const AVLTree = (function () {
}
// check if tree is balanced else balance it for insertion
const insertBalance = function (node, _val, balanceFactor) {
if (balanceFactor > 1 && _val < node._left._val) {
const insertBalance = function (node, _val, balanceFactor, tree) {
if (balanceFactor > 1 && tree._comp(_val, node._left._val) < 0) {
return rightRotate(node) // Left Left Case
}
if (balanceFactor < 1 && _val > node._right._val) {
if (balanceFactor < 1 && tree._comp(_val, node._right._val) > 0) {
return leftRotate(node) // Right Right Case
}
if (balanceFactor > 1 && _val > node._left._val) {
if (balanceFactor > 1 && tree._comp(_val, node._left._val) > 0) {
node._left = leftRotate(node._left) // Left Right Case
return rightRotate(node)
}
@ -140,7 +140,7 @@ const AVLTree = (function () {
}
updateHeight(root)
const balanceFactor = getHeightDifference(root)
return isValidBalanceFactor(balanceFactor) ? root : insertBalance(root, val, balanceFactor)
return isValidBalanceFactor(balanceFactor) ? root : insertBalance(root, val, balanceFactor, tree)
}
// delete am element

View File

@ -5,26 +5,38 @@ describe('AVLTree Implementation: ', () => {
const dataList = []
const demoData = [1, 4, 6, 22, 7, 99, 4, 66, 77, 98]
const avlStringTree = new AVLTree()
const collator = new Intl.Collator()
const stringData = ['S', 'W', 'z', 'B', 'a']
beforeAll(() => {
demoData.forEach(item => {
if (avlTree.add(item)) {
dataList.push(item)
}
})
avlStringTree._comp = collator.compare
stringData.forEach(item => avlStringTree.add(item))
})
it('checks if element is inserted properly', () => {
expect(dataList.length).toEqual(avlTree.size)
expect(stringData.length).toEqual(avlStringTree.size)
})
it('search if inserted element is present', () => {
demoData.forEach(data => {
expect(avlTree.find(data)).toBeTruthy()
})
stringData.forEach(data => {
expect(avlStringTree.find(data)).toBeTruthy()
})
})
it('deletes the inserted element', () => {
const deleteElement = dataList[3]
expect(avlTree.remove(deleteElement)).toBeTruthy()
expect(avlStringTree.remove(stringData[3])).toBeTruthy()
})
})