|
这道题可以分为好几种情况:
首先,节点只有左、右子树,没有parent指针,不是二叉搜索树
这种情况我们可以进行深度搜索,在某一节点下,我们进行深度搜索,如果其孩子正好有等于a子节点,则返回该子节点,同理可以适用于b子节点。
BinaryTreeNode* FindCommonParent(BinaryTreeNode* root, BinaryTreeNode* a, BinaryTreeNode* b)
{
if(root == NULL)
{
return NULL;
}
if(root == a || root == b)
{
return root;
}
BinaryTreeNode* left = FindCommonParent(root->lchild, a, b);
BinaryTreeNode* right = FindCommonParent(root->rchild, a, b);
if(left && right)
{
return root;
}
return left ? left : right;
}
|