Use recursion. if none of root, root->left and root->right equal to p or q, return NULL. If left and right are both not NULL, this root is the ancestor. If root equals to p or q, return the root to represent that at least one node is found. If left or right is not NULL, return it to represent at least one node is found in the subtree of this root.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root)
return NULL;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left&&right||root==p||root==q)
return root;
if(left)
return left;
if(right)
return right;
return NULL;
}
};
The code above can be accepted in the Lowest Common Ancestor of a Binary Tree. But it is not the fastest way in this problem. So I add a few conditions to do the pruning. The following is the updated code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root)
return NULL;
TreeNode* left,*right;
if(p->val>root->val&&q->val>root->val)
left=NULL;
else
left=lowestCommonAncestor(root->left,p,q);
if(p->val<root->val&&q->val<root->val)
right=NULL;
else
right=lowestCommonAncestor(root->right,p,q);
if(left&&right||root==p||root==q)
return root;
if(left)
return left;
if(right)
return right;
return NULL;
}
};