Skip to content

Commit

Permalink
Fixed SelfBalancingBinaryTree (#238)
Browse files Browse the repository at this point in the history
* Fixed SelfBalancingBinaryTree._left_rotate and SelfBalancingBinaryTree._right_rotate
  • Loading branch information
Aimaanhasan authored Apr 6, 2020
1 parent b2bc6c9 commit 307b13e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
10 changes: 8 additions & 2 deletions pydatastructs/trees/binary_trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,10 @@ def _right_rotate(self, j, k):
self.tree[j].left = y
self.tree[k].parent = self.tree[j].parent
if self.tree[k].parent is not None:
self.tree[self.tree[k].parent].left = k
if self.tree[self.tree[k].parent].left == j:
self.tree[self.tree[k].parent].left = k
else:
self.tree[self.tree[k].parent].right = k
self.tree[j].parent = k
self.tree[k].right = j
kp = self.tree[k].parent
Expand Down Expand Up @@ -617,7 +620,10 @@ def _left_rotate(self, j, k):
self.tree[j].right = y
self.tree[k].parent = self.tree[j].parent
if self.tree[k].parent is not None:
self.tree[self.tree[k].parent].right = k
if self.tree[self.tree[k].parent].left == j:
self.tree[self.tree[k].parent].left = k
else:
self.tree[self.tree[k].parent].right = k
self.tree[j].parent = k
self.tree[k].left = j
kp = self.tree[k].parent
Expand Down
31 changes: 30 additions & 1 deletion pydatastructs/trees/tests/test_binary_trees.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from pydatastructs.trees.binary_trees import (
BinarySearchTree, BinaryTreeTraversal, AVLTree,
ArrayForTrees, BinaryIndexedTree)
ArrayForTrees, BinaryIndexedTree, SelfBalancingBinaryTree)
from pydatastructs.utils.raises_util import raises
from pydatastructs.utils.misc_util import TreeNode
from copy import deepcopy
Expand Down Expand Up @@ -319,3 +319,32 @@ def test_BinaryIndexedTree():
assert t.get_sum(0, 2) == 105
assert t.get_sum(0, 4) == 114
assert t.get_sum(1, 9) == 54

def test_issue_234():
"""
https://github.com/codezonediitj/pydatastructs/issues/234
"""
tree = SelfBalancingBinaryTree()
tree.insert(5, 5)
tree.insert(5.5, 5.5)
tree.insert(4.5, 4.5)
tree.insert(4.6, 4.6)
tree.insert(4.4, 4.4)
tree.insert(4.55, 4.55)
tree.insert(4.65, 4.65)
original_tree = str(tree)
tree._right_rotate(3, 5)
assert tree.tree[3].parent == 5
assert tree.tree[2].right != 3
assert tree.tree[tree.tree[5].parent].right == 5
assert str(tree) == ("[(2, 5, 5, 1), (None, 5.5, 5.5, None), "
"(4, 4.5, 4.5, 5), (None, 4.6, 4.6, 6), "
"(None, 4.4, 4.4, None), (None, 4.55, 4.55, 3), "
"(None, 4.65, 4.65, None)]")
assert tree.tree[tree.tree[3].parent].right == 3
tree._left_rotate(5, 3)
assert str(tree) == original_tree
tree.insert(4.54, 4.54)
tree.insert(4.56, 4.56)
tree._left_rotate(5, 8)
assert tree.tree[tree.tree[8].parent].left == 8

0 comments on commit 307b13e

Please sign in to comment.