Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
LeetCode-235 : Given a binary search tree (BST), find the lowest common ancestor (LCA) node 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).”
Here are a few observations:
p
and q
are given to be always present, which means we can skip a couple of edge cases.Based on these observations, following is an algorithm to work with:
While traversing the tree:
p
and q
are greater than the root
node’s value, it means both nodes are in the right subtree. So, move to the right subtree of the root
node.p
and q
are less than the current node’s value, it means both nodes are in the left subtree. So, move to the left subtree of the root
node.p
or q
is on one side and the other is on the other side, or if one of them is equal to the current node, then the current node is the LCA.Note: one of them is equal to the current node \( \Rightarrow \) Consider the following illustration, for nodes 2 and 4, during tree traversal, when root
is pointing to 2
, it is equal to the p.val
.
Following is a java implementation of the above mentioned approach:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
// both the nodes less than the root value
// move to left subtree
if(p.val < root.val && q.val < root.val){
return lowestCommonAncestor(root.left, p, q);
}
// both the nodes greater than the root value
// move to left subtree
else if(p.val > root.val && q.val > root.val){
return lowestCommonAncestor(root.right, p, q);
}
// nodes are in separate subtrees
// or while traversing we have now
// reached at a stage where either of the nodes is equal
// to current root
return root;
}
This algorithm finds the LCA in \(O(h)\) time, where h
is the height of the BST.
Be notified of new posts. Subscribe to the RSS feed.