二叉搜索树在C++中的实现

Binary Search Tree implementation in C++

本文关键字:实现 C++ 搜索树      更新时间:2023-10-16
#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;
}

BST的这种实现有什么问题?我给出 8 个值作为输入:835168724但是当我调用打印函数时。我没有得到任何输出。我错过了一些指针逻辑吗?insert 函数以递归方式沿着树向下移动,以查找插入值的位置打印函数也可以递归工作。

让我们看一下 insert 函数中的这些行:

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

这里的问题是参数node按值传递的,就像任何其他局部变量一样,并且像任何其他局部变量一样,一旦函数返回,它就会超出范围,并且对变量的所有更改都将丢失。

你需要通过引用传递指针,比如

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

您永远不会在 BST 类中分配给 root,因为您对插入类中节点的赋值在插入函数之外不可见。您可以通过引用插入函数来传递 Node 指针来解决此问题:

void insert(Node*& node, int data)