C++ 在treap中添加错误
我意识到了treap,它有方法add。所以,当我主要做这件事的时候C++ 在treap中添加错误,c++,oop,tree,C++,Oop,Tree,我意识到了treap,它有方法add。所以,当我主要做这件事的时候 int main(){ nodeptr root=NULL; treap bst; bst.add(root, 10); // bst.add(root, 9); // bst.add(root, 8); if(bst.find(root, 10)){ cout<<"OMG"; } } 寻找 bool treap::find(nodeptr &
int main(){
nodeptr root=NULL;
treap bst;
bst.add(root, 10);
// bst.add(root, 9);
// bst.add(root, 8);
if(bst.find(root, 10)){
cout<<"OMG";
}
}
寻找
bool treap::find(nodeptr &p, int x){
if(!p){
return false;
}
if(p->x == x){
return true;
}
else if(x< p->x){
return find(p->left, x);
}
else{
return find(p->right, x);
}
}
以及我如何定义treap:
typedef struct node *nodeptr;
struct node{
int x;
long y;
node* left ;
node* right ;
int cnt;
node(int key=0, long prior=0): x(key), y(prior), left(NULL), right(NULL), cnt(0) {}
};
class treap{
public:
int cnt( nodeptr &p);
bool find(nodeptr &p, int x);
void update_cnt(nodeptr &p);
void split(nodeptr &p, int x, nodeptr &l, nodeptr &r);
void insert(nodeptr &p, nodeptr &q);
nodeptr merge(nodeptr l, nodeptr r);
void deletes(nodeptr &p, int x);
void add(nodeptr &p, int x);
};
请你给我解释一下,为什么这个错误在这里?先谢谢你。很抱歉,如果问题是nooby,我是oop的新手。行:
nodeptr-nv,l,r代码>只创建一个指向节点的指针,它不指向任何有用的东西。您应该为节点分配内存,并使此指针指向分配的内存。nodeptr nv=new node代码>(确保删除该内存)
更好的是,您可能希望创建控制该节点生存期的对象,而不是手动处理内存
nodeptr treap::merge(nodeptr l, nodeptr r){
nodeptr result;
if (!l){
result=r;
}
else if(!r){
result=l;
}
else if(l->cnt > r->cnt){
l->right=merge(l->right, r);
result=l;
}
else{
r->left=merge(l, r->left);
result=r;
}
return result;
}
typedef struct node *nodeptr;
struct node{
int x;
long y;
node* left ;
node* right ;
int cnt;
node(int key=0, long prior=0): x(key), y(prior), left(NULL), right(NULL), cnt(0) {}
};
class treap{
public:
int cnt( nodeptr &p);
bool find(nodeptr &p, int x);
void update_cnt(nodeptr &p);
void split(nodeptr &p, int x, nodeptr &l, nodeptr &r);
void insert(nodeptr &p, nodeptr &q);
nodeptr merge(nodeptr l, nodeptr r);
void deletes(nodeptr &p, int x);
void add(nodeptr &p, int x);
};