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

时间:2016-05-22 06:12:23

标签: c++ binary-search-tree

#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个值作为输入: 8 3 五 1 6 8 7 2 4 但是当我调用打印功能时。我没有得到任何输出。 我错过了一些指针逻辑吗? insert函数以递归方式向下移动到树中,以找到插入值的位置 打印功能也可以递归工作。

2 个答案:

答案 0 :(得分:3)

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

insert

这里的问题是参数if(node == NULL){ node = new Node(data); return; } 通过值传递并且像任何其他局部变量一样,并且像任何其他局部变量一样,一旦函数返回它将超出范围,并且对变量的所有更改都将丢失。

您需要的是通过引用传递指针,例如

node

答案 1 :(得分:1)

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

chan struct{}