設計並實現一個算法,找出二叉樹中某兩個節點的第一個共同祖先。不得將其他的節點存儲在另外的數據結構中。注意:這不一定是二叉搜索樹。
/**
* 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:
bool cover(TreeNode* root,TreeNode* t)
{
if(root == NULL)
return NULL;
if(root == t)
return root;
return cover(root->left,t) || cover(root->right,t);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!cover(root,p) || !cover(root,q))
return NULL;
if(root == NULL)
return NULL;
if(root == q || root == p)
return root;
bool is_leftq = cover(root->left,p);
bool is_leftp = cover(root->left,q);
if(is_leftq != is_leftp)
return root;
TreeNode* child_side = is_leftq ? root->left : root->right;
return lowestCommonAncestor(child_side,p,q);
}
};
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL)
return NULL;
if(root == q && root == p)
return root;
TreeNode* x = lowestCommonAncestor(root->left,p,q);
if(x != NULL && x != p && x != q)
{
return x;
}
TreeNode* y = lowestCommonAncestor(root->right,p,q);
if(y != NULL && y != p && y != q)
{
return y;
}
if(x != NULL && y != NULL)
return root;
else if(root == p || root == q)
return root;
else
return x == NULL ? y : x;
}