Fair Lowest Common AncestorMy Submissions
Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
4
/ \
3 7
/ \
5 6
For 3 and 5, the LCA is 4.
For 5 and 6, the LCA is 7.
For 6 and 7, the LCA is 7.
IDEA:
1. if root == null, return null
2. if root == A || B return root. In the case, we do not need to recurs. For example, If A = 6, B = 7, the algorithm first reach 7, and return 7. When backing up, "right" always return 7, and "left" always return null. After we backed up from the actual root node, 7 will be returned. Because the problem guarantee there the two such nodes exist in the tree. If we find one, we can immediately return and back. Then, if we find another one, we return the root for the two nodes. If not, the other nodes must be in the subtree by the node we found.
CASES ARE ALL VERY EASY! DO NOT THINK TOO MUCH!
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if(root == null || root == A || root == B) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
if(left != null && right != null) {
return root;
}
if(left != null) {
return left;
}
if(right != null) {
return right;
}
return null;
}
}