235 Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to thedefinition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allowa node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes2and8is6. Another example is LCA of nodes2and4is2, since a node can be a descendant of itself according to the LCA definition.
Solution)
According to BST's property, node's value is greater than value of left child and less than value of right child. We can find the lowest common ancestor using this feature. Repeat until the value of the root node is between the given two nodes.
We can use the iterative approach and recursion approach.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==null) return null;
while(true) {
if (Math.max(p.val, q.val) < root.val) root = root.left;
else if (Math.min(p.val, q.val) > root.val) root = root.right;
else return root;
}
}
}
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==null) return null;
if (Math.max(p.val, q.val) < root.val) return lowestCommonAncestor(root.left, p, q);
else if (Math.min(p.val, q.val) > root.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}