简体   繁体   中英

Node implementation Binary Tree

I have the following implementation for the node class:

template<class T> class binTree;          // forward declaration

template<class T> class Node {
friend class binTree<T>;                  // class binTree is friend

public:
    //default constructor
    Node(const T& d = T(), Node<T> *l = NULL, Node<T> *r = NULL) : data(d),
            left(l), right(r) {};

private:
    T data;
    Node<T> *left, *right;
};

I'm trying to define a new node a the root of my tree, but I keep getting compilation errors...

template<class T>
void binTree<T>::insert(Node<T>*& n, const T& d){
    if(n == NULL)
       root = Node<T>(d); 
}

I'm confused by the const T& d = T() parameter .

I think you just need to declare the binTree class and its members before you try to define the member. The following code compiles for me:

#include <cstdlib>

template<class T> class binTree;          // forward declaration

template<class T> class Node {
friend class binTree<T>;                  // class binTree is friend

public:
    //default constructor
    Node(const T& d = T(), Node<T> *l = NULL, Node<T> *r = NULL) : data(d),
            left(l), right(r) {};

private:
    T data;
    Node<T> *left, *right;
};

template <class T> class binTree
{
    public:
    binTree() { }
    void insert(Node<T>*& n, const T& d);

    private:
    Node<T> root;
};

template<class T>
void binTree<T>::insert(Node<T>*& n, const T& d){
    if(n == NULL)
       root = Node<T>(d); 
}



int main(int argc, char **argv)
{
    Node<int>* nt;
    binTree<int> btree;
    btree.insert(nt, 4);
}

Having said this, your concept of the data structure seems messed up. Why does the insert routine in binTree require a node argument?

I'm not quite sure why you have that default override for the d variable in your default constructor. In my implementation of a Node for my Tree class, I had no default assignment. I think the issue is T(). I would recommend not trying to do that default assignment in the params listing, but instead do it in the BMI List. So it would look kind of like "data(new T), left(NULL), right(NULL)"

Additionally I would say I'm not quite certain as to why you are using T(). If that doesn't work, please post the error code so that we can have a better understanding of what is going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM