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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
public class Solution235 {
public boolean findPath(TreeNode root, TreeNode p, List<TreeNode> result) {
if(root == null) return false;
if(root == p) {
result.add(root);
return true;
}
if(root.val >= p.val) {
result.add(root.left);
root = root.left;
} else {
result.add(root.right);
root = root.right;
}
findPath(root,p,result);
return true;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> listp = new ArrayList<TreeNode>();
List<TreeNode> listq = new ArrayList<TreeNode>();
listp.add(root);
listq.add(root);
findPath(root, p, listp);
findPath(root, q, listq);
TreeNode ans = root;
for (int i = 1, j = 1; i < listp.size() && j < listq.size(); i++, j++) {
if(listp.get(i).equals(listq.get(j))) {
ans = listp.get(i);
} else {
break;
}
}
return ans;
}
public static void main(String[] args) {
TreeNode p = null, q = null;
TreeNode root = new TreeNode(6);
root.left = new TreeNode(2);
p = root.left;
root.right = new TreeNode(8);
//q = root.right;
root.left.left = new TreeNode(0);
root.left.right = new TreeNode(4);
q = root.left.right;
root.left.right.left = new TreeNode(3);
root.left.right.right = new TreeNode(5);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(9);
TreeNode ans = new Solution235().lowestCommonAncestor(root, p, q);
System.out.println(ans.val);
}
}