二进制搜索树c++

Binary Search Tree c++

本文关键字:c++ 搜索树 二进制      更新时间:2023-10-16

请帮助我使用此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;
}

它编译甚至运行,但我得到的输出是:

Enter the size: 3
1
_2
_3
_

然而它应该是:

Enter the size: 3
1
_2
>_3
>>_

您正在更改insrta的值,但这只是输入参数的副本。改变insrta的值不会改变mainroot的值。

解决此问题的一种方法是从insrt返回有效节点并在main中使用它。

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;
}