二进制搜索树中最低的共同祖先

时间:2011-08-06 10:25:15

标签: c++ binary-search-tree

如果所有元素都不同,它很容易在BST中找到最接近的共同祖先。但是,如果某些值是相同的,那该怎么办呢?到目前为止我们只是比较节点的数据,那就是它,但现在我们需要检查节点的地址而不仅仅是值吗?

3 个答案:

答案 0 :(得分:1)

是的,不是仅使用key进行比较,而是使用(key, address of node)进行比较。这在处理非唯一键时简化了代码。

答案 1 :(得分:0)

如果没有看到你正在使用什么类型的结构,很难给出细节,但你可以尝试类似这样的伪代码:

struct BST {
    struct BST* parent;
    struct BST* left;
    struct BST* right;
    void* value;
}

find_common_ancestor(struct BST* x, struct BST* y)
{
    set<struct BST*> ancestors;

    // Add all of x's ancestors to set.
    while (true) {
        ancestors.insert(x);

        if (x == NULL)
            break;

        x = x=>parent;
    }

    // Check y's ancestors against x's until a match is found.
    while (true) {
        if (ancestors.count(y) > 0)
            return y;

        y = y->parent;
    }
}

答案 2 :(得分:0)

这是psudocode。只需将它们转换为语法。

GETLeastCommonAn(BINARYTREE BT, NODE A, NODE  B)
IF Root==NIL
    return NIL
ENDIF

IF Root==A OR root==B
    return Root
ENDIF

Left = GETLCA (Root.Left, A, B)
Right = GETLCA (Root.Right, A, B)

IF Left! = NIL AND Right! = NIL
    return root
ELSEIF Left! = NIL
    Return Left
ELSE
    Return Right
ENDIF
相关问题