简体   繁体   English

将节点添加到二进制搜索树C ++

[英]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. 在第一次添加调用之后,树“ test”的根仍然为空。 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? 我应该如何更改代码,以便在调用add并将节点移至树的正确位置时对其进行更新? Thank you very much! 非常感谢你!

You are passing the Node * by value here: 您正在按值传递Node *

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. 如果按值传递,则该函数仅接收Node *的副本,因此对它的任何修改都不会反映在调用代码中。

Also you might want to think about what happens when value is equal to the key . 另外,您可能需要考虑当value等于key时会发生什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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