二叉树 - 插入非空树
Binary Tree - Inserting into a Non-Empty Tree
我正在尝试创建二叉树,但在使用以下代码时遇到问题并收到错误:
expression must have pointer-to-class type.
我在 insert(tree->left, value) 和 insert( 树->右,值);
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;
}
假设node::left
和node::right
都是node*
类型,需要调用insert如下:
insert(&(*tree)->left, value);
或者,将 tree 作为指针引用传递并为自己省去一堆显式取消引用:
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;
}
我正在尝试创建二叉树,但在使用以下代码时遇到问题并收到错误:
expression must have pointer-to-class type.
我在 insert(tree->left, value) 和 insert( 树->右,值);
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;
}
假设node::left
和node::right
都是node*
类型,需要调用insert如下:
insert(&(*tree)->left, value);
或者,将 tree 作为指针引用传递并为自己省去一堆显式取消引用:
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;
}