Recursive
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
// it means one of them is the ancestor of the another
if (root == p || root == q) {
return root;
}
// if the root is not LCA, try to find it in the left tree
TreeNode leftLCA = lowestCommonAncestor(root.left, p, q);
// if the root is not LCA, try to find it in the right tree
TreeNode rightLCA = lowestCommonAncestor(root.right, p, q);
if (leftLCA == null) {
return rightLCA;
} else if (rightLCA == null) {
return leftLCA;
} else {
return root;
}
}
}