用c ++实现树

时间:2016-04-27 21:19:36

标签: c++ tree

我想实现一个二叉树,其中每个节点都包含leftright子树。以下是我班级的样子:

class KDTree
{
public:
    KDTree(...);   
    ~KDTree();

private:
    LatLng element; // The value of the node
    KDTree left;    // The left sub-tree
    KDTree right;   // The right sub-tree
};

然后我的构造函数看起来像这样:

KDTree::KDTree(...)
{   
    value = ...;
    if(not_finished)
    {
        left  = KDTree(...);
        right = KDTree(...);
    }
    else
    {
        left = NULL; // how to implement this properly ?
        right= NULL; // how to implement this properly ?
    }
}

如果我按照上面的说明尝试放置NULL,那么编译器会抱怨leftright属性未初始化。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

左右应该是这样的KDTree指针:KDTree * left,KDTree * right。然后Null将按原样使用

此外,在第一个if语句中,您可能需要更改

left = KDTree (...);
right = KDTree (...);

left = new KDTree (...);
right = new KDTree (...);

答案 1 :(得分:1)

这个例子不完整,所以我只是根据我所看到的内容进行猜测。

KDTree leftKDTree right是对象,而不是指针。因此,您无法为其分配NULL。尝试将它们变成指针:

class KDTree
{
    public:
        KDTree(...);   
        ~KDTree();
        // Note: You'll have to clean up your left and right trees in the destructor!

    private:
        LatLng element;   // The value of the node
        KDTree * left;    // The left sub-tree
        KDTree * right;   // The right sub-tree
};


KDTree::KDTree(...)
{   
    value = ...;
    if(not_finished)
    {
        left  = new KDTree(...); // recursive constructor call (nuh-uh! see below)
        right = new KDTree(...); // recursive constructor call (nuh-uh! see below)
    }
    else
    {
        left = NULL; // how to implement this properly ?
        right= NULL; // how to implement this properly ?
    }
}    

另外一个FYI:我看到你的"递归构造函数调用"在那里评论。那不太对劲。在原始代码中,left = KDTree(...); 以递归方式调用构造函数。它只是将新的KDTree分配给left(我猜测KDTree有一个赋值运算符)。

相关问题