/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
// Apply divide and conquer and throw the original question to left and right subtree: the subtrees either find the LCA or do not find it.
// Definition of the returned value from left and right subtrees:
// 1. NULL: find no LCA AND not even a node of A or B;
// 2. A node: either the LCA (both A and B nodes are in this subtree) or one of A and B nodes; to further determine which case it is, we need to look at the returned value of the other subtree: if the other subtree return NULL, then the returned node is LCA (since we are assured A and B nodes are in the tree); if the other subtree return a node, it means A and B nodes locate seperately in both left and right subtrees, and the LCA is the root node.
class Solution {
public:
/**
* @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.
*/
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
// Base case: when root == A (or B) no matter B (or A) locates, the LCA will be the root node;
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 && right == NULL) {
return left;
}
if (left == NULL && right != NULL) {
return right;
}
}
};