简体   繁体   中英

C++ binary search tree

Recently I have started playing around with C++, namely classes and pointers. I looked around for similar questions, but nothing helped.

I have a binary search tree class that holds some information in string format (well, char *), but after adding a new node to the tree, I cannot get the information back, as it returns junk.

Here is what my code looks like:

class Node
{
    Node *lNode;
    Node *rNode;
    char *name;
    public:
        void setName(char *n) { name = n; }
        char *getName() { return name; }
}

class Tree
{
    Node *root;
    Node *addNode(Node *, Node *);
    public:
        Tree() { root = NULL };
        int addNewNode(Node *);
        void print();
};

int Tree::addNewNode(Node *n)
{
    root = addNode(root, n);
    cout << root->getName() << endl;   // this returns the name correctly
}

Node *Tree::addNode(Node *subtree, Node *node)
{
    if(subtree== NULL)
    {
        subtree = node;
    }
    else if(node->getName() <= subtree->getLeft())
    {
        subtree->setLeft(addNode(subtree->getLeft(), node));
    }
    else
    {
        subtree->setRight(addNode(subtree->getRight(), node));
    }

    return subtree;
}

void Tree::print()
{
    cout << root->getName() << endl;    // this does not!
}

And this is where I call the methods:

Tree *myTree = new Tree();

Node *n = new Node();
n->setName(name);
myTree->addNewNode(n);

The tree variable is a private member attribute of an outer container class, and actually gets created outside that class to be passed into the constructor. When I invoke the addNewNode method, that adds a Node to the tree, but when I want to print out the name of the node stored in the root, it just comes up with junk. I guess there's a haywire pointer somewhere, but I cannot find it for the life of me.

Any help would be greatly appreciated.

When root is null, you set it to city rather than node. There's your problem.

I'll guess that you're passing in a string pointer name to setName and just copying the pointer to name (as opposed to reallocating and saving the string). Later, the original object is gone, and your object name is left pointing to garbage. Trying using std::string for name instead, or create your own memory with name = new char[ strlen(n) + 1 ] and strcpy/memcpy it in. And don't forget to delete [] name at object destruction if you go that route.

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