Reputation: 53
This is my function to return maximum element of left subtree and minimum element of right subtree
def Max(root):#this will return maximum element of left subtree
if root.left and not root.right:
return root.data
if root.right:
Max(root.right)
else:
Max(root.left)
def Min(root):#this will return minimum element of right subtree
if not root.left and not root.right:
return root.data
if root.left:
Min(root.left)
else:
Min(root.right)
def InorderPreSuc(root):
pre=Max(root.left)
suc=Min(root.right)
print(' predecessor {} and successor {}.format(pre,suc))
But my function wont return the values Why?
Upvotes: 1
Views: 512
Reputation: 111
Maximum of left subtree would be finding the max at root.left, similarly minimum of right subtree would be the min of root.right
To recursively find min or max:
# Max of a BST would be its rightmost element
def Max(root):
if root.right is not None:
Max(root.right)
return root.data
# Min of BST would be its leftmost element
def Min(root):
if root.left is not None:
Min(root.left)
return root.data
Now to find maximum of left subtree call Max(root.left). We can add another check for null value in case the root is null.
def Min(root):
if root is None:
return float("-inf")
if root.left is not None:
Min(root.left)
return root.data
Upvotes: 2