LCA
Example
4
/ \
3 7
/ \
5 6Note
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;
}
}Last updated