Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia:
“The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
p
and q
are present in the BST?p
and q
be the same node?Assuming:
p
and q
are present in the BST.p
and q
are distinct nodes.p
and q
are greater than the current node, move to the right subtree.p
and q
are less than the current node, move to the left subtree.p
or q
is smaller and the other is larger, then the current node is the LCA.Here’s the implementation in python:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# Start with the root node
current = root
# Iterate through the tree
while current:
# If both p and q are greater than parent
if p.val > current.val and q.val > current.val:
current = current.right
# If both p and q are lesser than parent
elif p.val < current.val and q.val < current.val:
current = current.left
else:
# We have found the split point i.e. the LCA node.
return current
h
is the height of the binary search tree.h
could be log(n)
for a balanced tree.h
could be n
for a degenerate (linked list-like) tree.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?