2016-04-27 112 views
1

我想实现一个二叉树,其中每个节点包含leftright子树。这里是我的课怎么样子:在C++中实现树

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性质没有初始化。我怎样才能正确地做到这一点?

+0

如果你有C++ 11,请考虑养成使用'nullptr'而不是'NULL'的习惯。你能显示你得到的确切错误吗? – kfsone

+2

如果每个'KDTree'包含两个'KDTree',那么你得到无限递归,大小是无限的。 – doug65536

+1

@Shiro你正在用这堂课改造一个方形轮子。除非是作业问题,否则您应该只抓取现有的一百万个实现中的一个,这些实现是模板化的,分配器意识到的,并且是异常安全的。 –

回答

2

左右两边应该是这样的KDTree指针:KDTree * left,KDTree * right。然后空将作为用于

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

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

left = new KDTree (...); 
right = new KDTree (...); 
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(...);确实是而不是递归调用你的构造函数。它只是分配一个新的KDTreeleft(我猜KDTree有一个赋值操作符)。

+0

我删除了“递归”,不要混淆人。 – dimitris93

+0

我不会再困惑:) –

+1

告诉我,在原始问题中sizeof(KDTree)是什么 - 选择任何平台。无限,对吧? – doug65536