2016-04-27 117 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