⬅ Previous Topic
Check if a Binary Tree is a Binary Search TreeNext Topic ⮕
Convert a Binary Tree into a Binary Search Tree⬅ Previous Topic
Check if a Binary Tree is a Binary Search TreeNext Topic ⮕
Convert a Binary Tree into a Binary Search Treep
and q
.p
and q
are less than the current node, move to the left child.p
and q
are greater than the current node, move to the right child.p
and q
.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lowestCommonAncestor(root, p, q):
current = root
while current:
if p.val < current.val and q.val < current.val:
current = current.left
elif p.val > current.val and q.val > current.val:
current = current.right
else:
return current
return None
# Example usage:
if __name__ == '__main__':
# Construct BST:
# 6
# / \
# 2 8
# / \ / \
# 0 4 7 9
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(8)
root.left.left = TreeNode(0)
root.left.right = TreeNode(4)
root.right.left = TreeNode(7)
root.right.right = TreeNode(9)
p = root.left # Node with value 2
q = root.left.right # Node with value 4
lca = lowestCommonAncestor(root, p, q)
print(lca.val) # Output should be 2
⬅ Previous Topic
Check if a Binary Tree is a Binary Search TreeNext Topic ⮕
Convert a Binary Tree into 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.