简体   繁体   中英

Add nodes to binary search tree c++

I am building a binary search tree. Now I am having a problem with adding a node to the tree.

void BinaryTree::add(int value, Node* node) {
    if(!node)
        node = new Node(value);
    else if(node->key < value)
        this->add(value, node->rightNode);
    else if(node->key > value)
        this->add(value, node->leftNode);
}

This code does not seem to work when I call:

BinaryTree test;
test.add(4, test.root);
test.add(1, test.root);
test.add(5, test.root);
test.add(2, test.root);
test.add(3, test.root);
test.add(7, test.root);
test.add(6, test.root);

After the first add call, the root of the tree 'test' is still empty. How shall I change the code so that it will be updated when I call add and the node goes to the correct place of the tree? Thank you very much!

You are passing the Node * by value here:

void BinaryTree::add(int value, Node* node) {

One solution is to pass by reference instead:

void BinaryTree::add(int value, Node *& node) {
                                      ^

If you pass by value the function is just receiving a copy of the Node * and so any modification to it will not be reflected back in the calling code.

Also you might want to think about what happens when value is equal to the key .

您递归地调用add函数,但是在那儿我看不到您实际上将leftNode或rightNode分配给传入的节点。

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