二叉树 - 插入非空树

时间:2015-04-07 13:40:35

标签: c++ binary-tree

我正在尝试创建二叉树,但我遇到以下代码时遇到问题并收到错误:

expression must have pointer-to-class type.

我在"树"中收到错误在插入内( - >左,值)和插入( - >右,值) ;

void insert(node **tree, int value){
if (*tree == nullptr){
    *tree = new node;
    (*tree)->data = value;
    (*tree)->left = nullptr;
    (*tree)->right = nullptr;
}

else 
    if (value < (*tree)->data)
        insert(tree->left, value);  

    else if (value >(*tree)->data)
        insert(tree->right, value);

else
    return; 

}

1 个答案:

答案 0 :(得分:1)

假设node::leftnode::right的类型为node*,则需要按如下方式调用insert:

insert(&(*tree)->left, value);

或者,将树作为指针引用传递给自己并保存一堆显式的解引用:

void insert(node *&tree, int value){
    if (tree == nullptr){
        tree = new node;
        tree->data = value;
        tree->left = nullptr;
        tree->right = nullptr;
    }
    else if (value < tree->data)
        insert(tree->left, value);  
    else if (value > tree->data)
        insert(tree->right, value);
    else
        return;
}