简体   繁体   English

C ++二进制搜索树插入实现

[英]C++ Binary Search Tree Insert Implementation

I'm trying to build a function to insert into a binary search tree, but I'm having a hard time figuring out why it won't work. 我正在尝试构建要插入到二进制搜索树中的函数,但是我很难弄清楚为什么它不起作用。 I understand fundamentally how the function is supposed to work, but based on the template I was given it seems as though I am to avoid creating a BST class but instead rely on the Node class and build the desired functions to work on that. 我从根本上理解了该函数应该如何工作,但是基于模板,我似乎避免创建BST类,而是依靠Node类并构建所需的函数来工作。 Here's the given template: 这是给定的模板:

#include <iostream>
#include <cstddef>

using std::cout;
using std::endl;

class Node {
    int value;
public:
    Node* left;       // left child
    Node* right;      // right child
    Node* p;          // parent
    Node(int data) {
        value = data;
        left = NULL;
        right = NULL;
        p  = NULL;
    }
    ~Node() {
    }
    int d() {
        return value;
    }
    void print() {
        std::cout << value << std::endl;
    }
};

function insert(Node *insert_node, Node *tree_root){
    //Your code here
}

The issue I'm having is when I implement the following code, where getValue is a simple getter method for Node: 我遇到的问题是当我实现以下代码时,其中getValue是Node的简单getter方法:

int main(int argc, const char * argv[]) {
     Node* root = NULL;
     Node* a = new Node(2);
     insert(a, root);
}

void insert(Node *insert_node, Node *tree_root){
    if (tree_root == NULL)      
        tree_root = new Node(insert_node->getValue());

The code appears to compile and run without error, but if I run another check on root after this, it returns NULL. 该代码似乎可以编译并没有错误地运行,但是如果我在此之后在root上运行另一个检查,它将返回NULL。 Any idea what I'm missing here? 知道我在这里缺少什么吗? Why is it not replacing root with a new node equal to that of insert_node? 为什么不用与insert_node相等的新节点替换root?

I also realize this doesn't appear to be the optimal way to implement a BST, but I am trying to work with the template given to me. 我也意识到这似乎不是实现BST的最佳方法,但是我正在尝试使用提供给我的模板。 Any advice would be appreciated. 任何意见,将不胜感激。

As Joachim said your issue relates to difference between passing parameter by reference and by value. 正如Joachim所说,您的问题与按引用传递值和按值传递参数之间的差异有关。

In your code void insert(Node *insert_node, Node *tree_root) you pass Node* tree_root by value. 在代码void insert(Node *insert_node, Node *tree_root) ,按值传递Node* tree_root Inside the function you change local copy of this pointer, so outer value is not changed. 在函数内部,您可以更改此指针的本地副本,因此外部值不会更改。

To fix it you should pass Node* tree_root by reference . 要修复它,您应该通过reference传递Node* tree_root Parameter declaration can be Node*& tree_root (or Node** tree_root ). 参数声明可以是Node*& tree_root (或Node** tree_root )。 Eg: 例如:

void insert(Node* insert_node, Node*& tree_root){
    if (tree_root == NULL)      
        tree_root = new Node(insert_node->getValue());

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

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