#BST
class Node:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
def search(root, k):
if root is None or root.val == k:
return root
elif root.val < k:
return search(root.right, k)
else:
return search(root.left, k)
def minimum(root):
if root is None or root.left is None:
return root
return minimum(root.left)
def maximum(root):
if root is None or root.right is None:
return root
return maximum(root.right)
def successor(root, node):
if node.right is not None:
return minimum(node.right)
succ = None
while root is not None and root.val != node.val:
if root.val > node.val:
succ = root
root = root.left
else:
root = root.right
return succ
def predecessor(root, node):
if node.left is not None:
return maximum(node.left)
else:
pred = None
while root is not None and root.val != node.val:
if root.val > node.val:
root = root.left
else:
pred = root
root = root.right
return pred
def insert(root, key):
if root is None:
return Node(key)
elif root.val < key:
return Node(root.val, root.left, insert(root.right, key))
else:
return Node(root.val, insert(root.left, key), root.right)
def parent(root, node):
if root is None:
return root
elif (root.left is not None and root.left.val == node.val) or \
(root.right is not None and root.right.val == node.val):
return root
else:
if root.val < node.val:
return parent(root.right, node)
else:
return parent(root.left, node)
def delete(root, node):
p = parent(root, node)
if node.left is None or node.right is None:
replacement = node.left if node.left is None else node.right
if p is None:
root = replacement
elif p.val < node.val:
p.right = replacement
else:
p.left = replacement
else:
replacement = successor(root, node)
succ_parent = parent(root, replacement)
succ_parent.left = replacement.right
node.val = replacement.val
return root
Require code review in terms of correctness, style consistency, efficiency, code readability, and "pythonic"ness. (I, of course, welcome any other comments on the code as well)
I know that this a bit big to review completely. Reviewing only one or more methods will be appreciated.
Also, the WikiPage talks about designing persistent data structures. When should one consider such design and what are the advantages?
Github: https://github.com/abhisheksp/algorithms (the repo has the test cases)
if not Noneis very redundant. None type in python has a truthy value of false. You can jut sayif root.right:and the code will then execute if it exists, and will not if it doesn't. This alone will make your code much more readable. \$\endgroup\$