Add nodes to binary search tree c++

前提是你 提交于 2020-01-17 00:37:09

问题


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!


回答1:


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.




回答2:


You recursively call the add function, but nowhere in there do I see you actually assigning leftNode or rightNode to the passed in node.



来源:https://stackoverflow.com/questions/17555521/add-nodes-to-binary-search-tree-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!