⬅ Previous Topic
Find the Inorder Successor in a Binary Search TreeNext Topic ⮕
Check if a Binary Tree is a Binary Search Tree⬅ Previous Topic
Find the Inorder Successor in a Binary Search TreeNext Topic ⮕
Check if a Binary Tree is a Binary Search Treeclass TreeNode:
def __init__(self, val=0, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def inorderPredecessor(node):
if node.left:
pred = node.left
while pred.right:
pred = pred.right
return pred
curr = node
while curr.parent and curr == curr.parent.left:
curr = curr.parent
return curr.parent
# Example usage:
if __name__ == '__main__':
# Construct BST:
# 20
# / \
# 10 30
#
# 15
root = TreeNode(20)
root.left = TreeNode(10, parent=root)
root.right = TreeNode(30, parent=root)
root.left.right = TreeNode(15, parent=root.left)
node = root.left.right
pred = inorderPredecessor(node)
if pred:
print(f'Inorder predecessor of {node.val} is {pred.val}')
else:
print('No inorder predecessor found')
⬅ Previous Topic
Find the Inorder Successor in a Binary Search TreeNext Topic ⮕
Check if a Binary Tree is a Binary Search TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.