简体   繁体   English

C ++中的二进制搜索树实现

[英]Binary Search Tree implementation in C++

#include <iostream>
using namespace std;

class Node{
    public:
        int data;
        Node* left_child;
        Node* right_child;
        Node(int x){
            data = x;
            left_child = NULL;
            right_child = NULL;
        }
};

class BST{
    public:
    //Initially root is null
    Node* root = NULL;

    void insert(Node* node, int data){
        if(node == NULL){
            node = new Node(data);
            return;
        }
        if(data < node->data){
            insert(node->left_child,data);
        }
        else if(data > node->data){
            insert(node->right_child,data);
        }

    }
    void just_insert(int data){
        insert(root,data);
    }
    void print(Node* node){
        if(node == NULL){
            return;
        }
        cout<<node->data<<" ";
        print(node->left_child);
        print(node->right_child);
    }
    void just_print(){
        print(root);
    }
};

int main() {
    //For fast IO
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n,x;
    cin>>n;
    BST bst = BST();
    for(int i=0; i<n; i++){
        cin>>x;
        bst.just_insert(x);
    }
    bst.just_print();
    return 0;
}

What is wrong with this implementation of BST ? BST的这种实现有什么问题? I am giving 8 values as input: 8 3 5 1 6 8 7 2 4 But when I invoke the print function. 我提供8个值作为输入:8 3 5 1 6 8 7 2 4但是,当我调用print函数时。 I do not get any output. 我没有任何输出。 Am I missing out on some pointer logic ? 我是否错过了一些指针逻辑? The insert function goes recursively down the tree, to find a place to insert the value The print function also works recursively. insert函数以递归方式在树上向下移动,以找到插入值的位置。print函数也以递归方式工作。

Lets take a look at these lines from the insert function: 让我们从insert函数看一下这些行:

if(node == NULL){
    node = new Node(data);
    return;
}

The problem here is that the argument node is passed by value and is like any other local variable, and like any other local variable it will go out of scope once the function returns, and all changes to the variable will be lost. 这里的问题是参数node是通过传递 ,就像任何其他局部变量一样,并且像任何其他局部变量一样,一旦函数返回,它将超出范围,并且对该变量的所有更改都将丢失。

What you need is to pass the pointer by reference , like 您需要通过引用传递指针,例如

void insert(Node*& node, int data){ ... }
//               ^
// Note ampersand here

You never assign to root in your BST class because your assignment to node in the insert class is not visible outside the insert function. 您绝不会在BST类中分配给root用户,因为在insert函数外部看不到您对insert类中的节点的分配。 You can fix this by passing the Node pointer by reference to the insert function: 您可以通过将Node指针通过引用传递给insert函数来解决此问题:

void insert(Node*& node, int data)

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

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