[英]Why does this binary search tree cause a stack overflow?
#include<iostream>
using namespace std;
/*main idea is to construct ordered statistic tree,which is similar of
binary search tree,width addition of one key,which shows us it's rank in given
tree,for this i introduced additional one key-rank
*/
struct node
{
int val;
node *left,*right;
int rank;
node(int t) { val=t;left=right=NULL;}
};
node *root;
void insert(node *p,int ele)
{
if(p==NULL){
p=new node(ele);
return ;
}
else if(ele<p->val)
{
insert(p->left,ele);
}
else if(ele>p->val)
{
insert(p->right,ele);
}
}
void inorder (node *p)
{
if(p!=NULL){ inorder(p->left);
cout<<p->val<<" "<<p->rank;
inorder(p->right);
}
}
int count_node(node *t)
{
int sum=0;
if(t==NULL) return 0;
else sum=1;
if(t->left) sum+=count_node(t->left);
if(t->right) sum+=count_node(t->right);
return sum;
}
int main()
{
root=NULL;
root->rank=0;
insert(root,26);
insert(root,17);
insert(root,41);
insert(root,14);
insert(root,30);
insert(root,21);
insert(root,47);
insert(root,10);
insert(root,16);
insert(root,28);
insert(root,38);
insert(root,35);
insert(root,39);
insert(root,19);
insert(root,21);
insert(root,20);
insert(root,7);
insert(root,12);
insert(root,3);
inorder(root);
return 0;
}
這段代碼會導致溢出,但是我不明白為什么,因為我已經正確構造了構造函數。
問題是:
root=NULL;
root->rank=0;
這會導致不確定的行為,因為您取消引用了NULL
指針。 什么都可能發生。
也:
void insert(node *p,int ele)
{
if(p==NULL){
p=new node(ele);
return ;
}
//...
}
這不會修改原始指針。 如果在NULL
指針上調用insert
,則函數返回時將為NULL
。 您需要通過引用傳遞它:
void insert(node *& p,int ele)
除了陸謙所說的之外,您還存在以下問題:
void insert(node *p,int ele)
{
if(p==NULL){
p=new node(ele);
return ;
}
....
指針p
按值傳遞。 當您說p=...
您正在更改僅對函數可見的指針的副本。 您可能需要引用要更改的指針:
void insert(node *&p, int ele){ ... }
您的main
功能的前兩行有一個很大的問題:
root=NULL;
root->rank=0;
如果您在上面查看自己的定義,則將root
定義為節點指針 ,即它不會為實際節點保留任何空間。
如果您自己不保留空間,那么您將嘗試寫入未初始化的內存。 而且,您明確地說根指向什么也沒有 ,那就是NULL
。 在下一行中,您嘗試訪問它的名為rank
的成員。
您應該嘗試替換該行:
root = NULL;
用
root = new node(0);
或類似的東西實際上保留了空間並構造了一個節點。
或者,您可以嘗試在最后將等級提升到根,因為如果沒有insert
功能,則insert
函數實際上會構造根。 編輯為Luchian說,你只嘗試構建根的insert
方法。 如果您按照他的建議重新編寫insert方法,那么僅移動root->rank=0;
可能就可以工作root->rank=0;
行到插入過程的結尾。
root=NULL;
root->rank=0;
這可能是問題,您不應引用NULL
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.