简体   繁体   中英

Binary Search Tree Data in Nodes always is zero

I've been working on my Binary search tree for a while and the functions seem to work but I'm running into the same problem I had when I had a linked list program assignment. My nodes don't seem to want to store data. I can't figure out what the problem is. When I print it only prints zeros, the correct number of zeros, but still just zeros. Here's my code for my node. I should mention this is C++.

class Node{
    friend class BST;
    private:
    int data;
    Node *left;
    Node *right;
    public:
    Node(int data);   
};

My add function is:

void BST::add(Node* node, int d) {
    if (root == NULL) {
        root = new Node(d);
    }
    else if (d <= node->data) {
        if (node->left == NULL) {
            node->left = new Node(d);
        }
        else {
            add(node->left, d);
        }
    }
    else if (d > node->data) {
        if (node->right == NULL) {
            node->right = new Node(d);
        }
        else {
            add(node->right, d);
        }
    }
}

Why won't it store data?

Please modify your Node::Node(int) into:

Node::Node(int data) {
    left = NULL;
    right = NULL;
    this->data = data;
}

Your Node::Node() described in your comment does not store the data at all; and your BST::add() relies on it to store values into Node s.

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