二进制搜索树c++
Binary Search Tree 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;
}
它编译甚至运行,但我得到的输出是:
Enter the size: 3
1
_2
_3
_
然而它应该是:
Enter the size: 3
1
_2
>_3
>>_
您正在更改insrt
中a
的值,但这只是输入参数的副本。改变insrt
中a
的值不会改变main
中root
的值。
解决此问题的一种方法是从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;
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 二叉搜索树的 C++ 实现中的EXC_BAD_ACCESS错误
- 删除二叉搜索树 (C++) 中的单个元素
- 将值存储在带有C++的二叉搜索树中
- 二叉搜索树未将插入值加载到树中
- 二叉搜索树使用最常用的节点来打印出某些语句
- 如何以特定格式C++打印二叉搜索树