现在的位置: 首页 > 综合 > 正文

找出树中两个节点的最低公共祖先

2013年04月13日 ⁄ 综合 ⁄ 共 472字 ⁄ 字号 评论关闭

关于这道题,可以将其转化为求两个单链表的第一个焦点,这种做法需要两个栈,分别存储根节点到给定节点的路径。

下面给出新的解法,利用后根遍历,代码如下:

bool findCommonFather(treenode *root, char a, char b)          //a不一定是左节点,b不一定是右节点
{
    bool left = false, right = false;

    if(root->lchild != NULL)
    {
        left = findCommonFather(root->lchild, a, b);
    }
    if(root->rchild != NULL)
    {
        right = findCommonFather(root->rchild, a, b);
    }

    if(root->data == a)
    {
        if(left)
        {
            right = true;
        }
        else
        {
            left = true;
        }
    }
    else if(root->data == b)
    {
        if(right)
        {
            left = true;
        }
        else
        {
            right = true;
        }
    }

    if(left && right)
    {
        cout<<root->data<<endl;
    }
    return left || right;
}

抱歉!评论已关闭.