If there is parent pointers, trace back along the parent pointers and when those two parents intersect, that is the common ancestor. But this need a table for visited nodes.
If there is no parent pointers, when those two nodes are at the different sides of a node, that node is the common ancestor, otherwise, they are at the same side (left or right) of a node.
Code:
bool cover(TreeNode* root, TreeNode* p) // check whether p is a node in the tree
{
if (root==NULL) return false;
if (root==p) return true;
return cover(root->left, p) || cover(root->right, p);
}
TreeNode* checkhelper(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root==NULL) return NULL;
if (root==p || root==q) return root;
if ( cover(root->left, p)!=cover(root->left, q) ) return root;
TreeNode* childnode;
childnode = cover(root->left,p) ? root->left : root->right;
return checkhelper(childnode, p, q);
}
TreeNode* commonancestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root==NULL) return NULL;
if ( !cover(root,p) || !cover(root,q) ) return NULL;
return checkhelper(root, p,q);
}
Optimized version:
No comments:
Post a Comment