Skip to content

Commit

Permalink
Added implementation for Splay Trees.
Browse files Browse the repository at this point in the history
Added code for splay trees with public APIs insert, delete, splay. The work is in reference with issue codezonediitj#109
  • Loading branch information
Vanshika266 committed Mar 15, 2020
1 parent 19cabb2 commit 7b94192
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pydatastructs/trees/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
)

from .binary_trees import (
TreeNode, BinaryTree, BinarySearchTree, BinaryTreeTraversal, AVLTree
TreeNode, BinaryTree, BinarySearchTree, BinaryTreeTraversal, AVLTree, SplayTree
)
__all__.extend(binary_trees.__all__)

Expand Down
67 changes: 66 additions & 1 deletion pydatastructs/trees/binary_trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
'AVLTree',
'BinaryTree',
'BinarySearchTree',
'BinaryTreeTraversal'
'BinaryTreeTraversal',
'SplayTree'
]

class BinaryTree(object):
Expand Down Expand Up @@ -783,3 +784,67 @@ def breadth_first_search(self, node=None, strategy='queue'):
if tree[node].right is not None:
q.append(tree[node].right)
return visit


class SplayTree(AVLTree):
"""
Represents Splay Trees.
References
==========
[1] https://en.wikipedia.org/wiki/Splay_tree
"""
def _zig(self,x,p):
if(self.tree[p].left==x):
super(SplayTree,self)._right_rotate(p,x)
else:
super(SplayTree,self)._left_rotate(p,x)

def _zig_zig(self,x,p):
super(SplayTree,self)._right_rotate(self.tree[p].parent,p)
super(SplayTree,self)._right_rotate(p,x)

def _zig_zag(self,x,p):
super(SplayTree,self)._left_rotate(p,x)
super(SplayTree,self)._right_rotate(self.tree[x].parent,x)

def _zag_zag(self,x,p):
super(SplayTree,self)._left_rotate(self.tree[p].parent,p)
super(SplayTree,self)._left_rotate(p,x)

def _zag_zig(self,x,p):
super(SplayTree,self)._right_rotate(p,x)
super(SplayTree,self)._left_rotate(self.tree[x].parent,x)

def splay(self,x,p):
while self.tree[x].parent is not None:
if(self.tree[p].parent is None):
self._zig(x,p)
elif(self.tree[p].left==x and self.tree[self.tree[p].parent].left == p):
self._zig_zig(x,p)
elif(self.tree[p].right==x and self.tree[self.tree[p].parent].right == p):
self._zag_zag(x,p)
elif(self.tree[p].left==x and self.tree[self.tree[p].parent].right == p):
self._zag_zig(x,p)
else:
self._zig_zag(x,p)
p = self.tree[x].parent


def insert(self,key,x):
super(AVLTree, self).insert(key, x)
e, p = super(AVLTree,self).search(x,parent=True)
self.tree[self.size-1].parent = p;
self.splay(e, p)

def delete(self,x):
b = super(AVLTree,self).delete(x,balancing_info=True)
self.splay(b,self.tree[b].parent)
return True

def join(self,tree2):
raise NotImplementedError("This is not implemented yet.")


def split(self,x):
raise NotImplementedError("This is not implemented yet.")

0 comments on commit 7b94192

Please sign in to comment.