二进制搜索树C++ 请帮助我学习C++ C++初学者:P 它被窃听了。。。请告诉我哪里出了问题! 注意:我使用cout调试 #include<iostream> using namespace std; struct node { int val; node* left; node* right; }*root; void insrt(node* a,int n) { if(a==NULL) { a=new node; a->val=n; a->left=NULL; a->right=NULL; cout<<"_"; } else if(a->val>n) { cout<<"<"; insrt(a->left,n); } else { cout<<">"; insrt(a->right,n); } } int main() { int n,x,i; cout<<"Enter the size: "; cin>>n; root=NULL; for(i=0;i<n;i++) { cin>>x; insrt(root,x); } return 0; }
然而,它应该是:二进制搜索树C++ 请帮助我学习C++ C++初学者:P 它被窃听了。。。请告诉我哪里出了问题! 注意:我使用cout调试 #include<iostream> using namespace std; struct node { int val; node* left; node* right; }*root; void insrt(node* a,int n) { if(a==NULL) { a=new node; a->val=n; a->left=NULL; a->right=NULL; cout<<"_"; } else if(a->val>n) { cout<<"<"; insrt(a->left,n); } else { cout<<">"; insrt(a->right,n); } } int main() { int n,x,i; cout<<"Enter the size: "; cin>>n; root=NULL; for(i=0;i<n;i++) { cin>>x; insrt(root,x); } return 0; },c++,binary-search-tree,C++,Binary Search Tree,然而,它应该是: Enter the size: 3 1 _2 >_3 >>_ 您正在更改insrt中a的值,但这只是输入参数的副本。更改insrt中a的值不会更改main中root的值 解决此问题的一种方法是从insrt返回有效节点,并在main中使用它 Enter the size: 3 1 _2 >_3 >>_ node* insrt(node* a,int n) { if(a==NULL) { a=new node;
Enter the size: 3
1
_2
>_3
>>_
您正在更改insrt中a的值,但这只是输入参数的副本。更改insrt中a的值不会更改main中root的值 解决此问题的一种方法是从insrt返回有效节点,并在main中使用它
Enter the size: 3
1
_2
>_3
>>_
node* insrt(node* a,int n)
{
if(a==NULL)
{
a=new node;
a->val=n;
a->left=NULL;
a->right=NULL;
cout<<"_";
return a;
}
else if(a->val>n)
{
cout<<"<";
a->left = insrt(a->left,n);
}
else
{
cout<<">";
a->right = insrt(a->right,n);
}
return a;
}
int main()
{
int n,x,i;
cout<<"Enter the size: ";
cin>>n;
root=NULL;
for(i=0;i<n;i++)
{
cin>>x;
root = insrt(root,x);
}
return 0;
}