For binary tree, to find the LCA, need to check for the node matching.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root.val == p.val || root.val == q.val) {
return root;
}
TreeNode leftResult = lowestCommonAncestor(root.left, p, q);
TreeNode rightResult = lowestCommonAncestor(root.right, p, q);
if (leftResult != null && rightResult != null) {
return root;
}
return leftResult != null ? leftResult : rightResult;
}
}
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val > q.val) {
return lowestCommonAncestor(root, q, p);
}
if (root == null || (p.val <= root.val && q.val >= root.val)) {
return root;
}
if (q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
} else {
return lowestCommonAncestor(root.right, p, q);
}
}
}