我想實現一個二叉樹,其中每個節點包含left
和right
子樹。這裏是我的課怎麼樣子:在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
正如我在上面,那麼編譯器抱怨left
和right
性質沒有初始化。我怎樣才能正確地做到這一點?
如果你有C++ 11,請考慮養成使用'nullptr'而不是'NULL'的習慣。你能顯示你得到的確切錯誤嗎? – kfsone
如果每個'KDTree'包含兩個'KDTree',那麼你得到無限遞歸,大小是無限的。 – doug65536
@Shiro你正在用這堂課改造一個方形輪子。除非是作業問題,否則您應該只抓取現有的一百萬個實現中的一個,這些實現是模板化的,分配器意識到的,並且是異常安全的。 –