【发布时间】:2020-04-14 19:51:00
【问题描述】:
我对 C++ 编码比较陌生。我正在尝试在 C++ 中创建 BST,并且为此使用了指针,但即使花费了数小时的时间,我也无法弄清楚指针中的错误。基本上,错误出现在 if 语句中,当父根存在孩子时,我尝试使用递归来更改根。
这是代码
#include<iostream>
using namespace std;
struct node{
struct node* rightchild;
int data;
struct node* leftchild;
};
struct node* newNode(int data){
struct node* node1 = (node*)malloc(sizeof(node));
(*node1).data=data;
(*node1).leftchild = NULL;
(*node1).rightchild = NULL;
return node1;
}
void insertIntoBST(struct node** ptrtoroot, struct node** ptrtotemp){
if((**ptrtotemp).data <= (**ptrtoroot).data){
if((**ptrtoroot).leftchild != NULL){
insertIntoBST((*ptrtoroot).leftchild,(*ptrtotemp));
}
else{
(*ptrtoroot->leftchild) = *ptrtotemp;
}
}
if((**ptrtotemp).data > (**ptrtoroot).data){
if((**ptrtoroot).rightchild != NULL){
insertIntoBST((*ptrtoroot->rightchild),(*ptrtotemp));
}
else{
(*ptrtoroot->rightchild) = *ptrtotemp;
}
}
}
void inorder(struct node* root){
while(root != NULL){
cout<<(*root).data;
inorder((*root).leftchild);
inorder((*root).rightchild);
}
}
int main(){
struct node* root = NULL;
struct node* temp;
int dat;
for(int i = 0 ; i < 6 ; i++){
cin>>dat;
temp = newNode(dat);
if(root == NULL){
root = temp;
}
else{
insertIntoBST(&root,&temp);
}
}
inorder(root);
return 0;
}
错误代码:
bst.cpp:21:40: error: request for member ‘leftchild’ in ‘* ptrtoroot’, which is of pointer type ‘node*’ (maybe you meant to use ‘->’ ?)
21 | insertIntoBST((ptrtoroot).leftchild,(*ptrtotemp));
| ^~~~~~~~~ bst.cpp:24:25: error: request for member ‘leftchild’ in ‘ ptrtoroot’, which is of pointer type ‘node*’ (maybe you meant to use ‘->’ ?)
24 | (*ptrtoroot->leftchild) = *ptrtotemp;
【问题讨论】:
-
我对 c++ 编码相对较新 -- 代码都是
C,几乎没有任何 C++(如果有的话)。 -
@PaulMcKenzie
#include<iostream>做到了技术上C++,但我同意你的看法;这是C代码。你不会这样用 C++ 写这个。 -
顺便说一句,在 C++ 中,声明函数参数时不需要关键字
struct。这在 C 中是必需的。您使用哪种语言进行编程? -
由于您使用 C++ 编程,您应该将节点方法放在
struct中。此外,更喜欢使用operator new到malloc,因为malloc不会调用struct构造函数。 -
在 C++ 中,您可以通过引用传递,这消除了通过指针传递的需要。指针可以指向任何地方并且难以验证(测试指针是否指向有效的内存位置)。通过引用传递更安全。
标签: c++ pointers binary-search-tree