2017-04-11 103 views
0

我正在使用STD向量製作二叉樹。我顯著削減下來,但低於總體思路是:數組和二叉樹的構造函數

template <class DataType> 
class ArrayNode 
{ 
protected: 
    DataType* _info; 
    int _left; //index position of left node 
    int _right;//index position of right node 

public: 
    ArrayNode(const DataType& info, int left, int right); 
    virtual ~ArrayNode(); 
    DataType& getInfo(); 
} 

template <class DataType> 
class ArrayBinaryTree 
{ 
protected: 
    vector<ArrayNode<DataType>* >* theBinaryTree; 
    int _root; 
    int _numOfNodes; 
    int _size; 
    //etc. 
public: 
    ArrayBinaryTree(DataType info); 
    virtual ~ArrayBinaryTree(); 
} 

你會如何創建一個構造函數,讓你可以與getInfo()訪問節點?我的想法是這樣:

std::vector<ArrayNode<DataType>*> binaryTree(1); 

ArrayBTNode<DataType>* element = new ArrayNode<DataType>(info, -1, -1); //some generic data 
binaryTree.insert(binaryTree.begin(), 1, element); 
theBinaryTree = &binaryTree; 

然後用類似(*theBinaryTree->at(0)).getInfo()訪問。 但是,使用這種類型的構造函數,getInfo()返回null。什麼是建立訪問構造函數的更好方法?

+3

您正在使用在函數結束時被銷燬的向量的地址。 –

+3

這麼多的指針。爲什麼這麼多指針? (我有一種可怕的感覺,ArrayNode :: ArrayNode'也說'_info = &info;') – molbdnilo

+1

所有'*'讓我頭暈 – user463035818

回答

3

讓我稍微改變一下界面,因爲我沒有看到將矢量保存爲指針的要點。這同樣適用於存儲在向量數據以及用於在節點數據:

template <class DataType> 
class ArrayNode 
{ 
protected: 
    DataType _info; 
    // ... rest of ArrayNode interface 
} 

template <class DataType> 
class ArrayBinaryTree { 
protected: 
    vector<ArrayNode<DataType> > theBinaryTree; // not pointers anymore 
    int _root = -1; // something that tells you no values are present 
    // You need size and numOfNodes attributes 
    // You get both of these things by calling size() method of std::vector 
    // etc. 
public: 
    ArrayBinaryTree(DataType info); 
    virtual ~ArrayBinaryTree(); 
} 

構造器可以例如實現像這樣的(假設它初始化根節點):

ArrayBinaryTree(DataType info) { 
    theBinaryTree.push_back(ArrayNode<DataType>(info, -1, -1)); 
    _root = 0; 
} 

甚至更​​好,你可以使用初始化列表:

ArrayBinaryTree(DataType info) 
     : theBinaryTree({ ArrayNode<DataType>(info, -1, -1) }), 
     _root(0) {} 

我不知道你是否有過載體,或者如果它實現它只是你的設計選擇。如果這只是您的設計選擇,我會建議重新設計它。假設這個簡化的接口:

template< typename T > 
struct Node { 
    T _value; 
    std::unique_ptr<Node> _left; 
    std::unique_ptr<Node> _right; 

    Node(const T& val) : _value(val) {} 
}; 

template < typename T > 
class BinTree { 
    std::unique_ptr<Node<T>> _root; 
public: 
    // methods 
}; 

我覺得這樣的設計對樹結構好得多。如果你有興趣,我可以寫更多。 注意:std :: unique_ptr是在C++ 11中引入的,所以如果你在老版本的標準原始指針中寫入,將不得不做(=更多的工作)。