4.7 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* LCA(TreeNode *root, TreeNode *a, TreeNode *b) {
if (root == NULL) {
return NULL;
}
if (root == a || root == b) {
return root;
}
TreeNode *left = LCA(root->left, a, b);
TreeNode *right = LCA(root->right, a, b);
if (left && right) {
return root;
} else {
return left ? left : right;
}
}