public class Solution {
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
//root A or B (itself)
if (root == null || root == A || root == B) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
//left/right departed -> root
if (left != null && right != null) {
return root;
}
//only A or B return A or B
if (left != null) {
return left;
}
if (right != null) {
return right;
}
//none for both
return null;
}
}
Brute Force, O(n^2)/O(nlogn)/O(nh)
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return root;
if (root.val == p.val) return p;
if (root.val == q.val) return q;
if (containsNode(root.left, p) && containsNode(root.left, q)){
return lowestCommonAncestor(root.left, p, q);
}
if (containsNode(root.right, p) && containsNode(root.right, q)){
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
private boolean containsNode(TreeNode root, TreeNode node){
if (root == null) return false;
if (root.val == node.val) return true;
return (containsNode(root.left, node) || containsNode(root.right, node));
}
}