二进制搜索树问题
Binary Search tree problem
我在这个程序中遇到了分段错误。这个流程似乎是正确的,正如我所想的那样。请帮我找出这个程序中的错误。
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
typedef struct node* Node;
void insert(Node,int);
Node root = NULL;
int main()
{
insert(root,2);
insert(root,1);
insert(root,3);
cout<<root->data<<" "<<root->left->data<<" "<<root->right->data<<endl;
return 0;
}
void insert(Node nod,int val)
{
if(nod == NULL)
{
Node newnode = new(struct node);
newnode->data = val;
newnode->left = NULL;
newnode->right = NULL;
nod = newnode;
if(root == NULL)
{
root = newnode;
}
}
else if(nod->data > val)
{
insert(node->left,val);
}
else if(nod->data < val)
{
insert(nod->right,val);
}
}
没有实际设置root->left
或root->right
的内容。对insert(node->left, val)
的调用并没有做你认为它会做的事情。为了实际修改左指针和右指针,你需要传递要插入的指针的地址。即insert(&node->left, val)
,并更改insert
来处理它。
它很简单。将插页更改为:
void insert(Node &nod,int val)
{
if(nod == NULL) {
Node newnode = new(struct node);
newnode->data = val;
newnode->left = NULL;
newnode->right = NULL;
nod = newnode;
}
else if(nod->data > val)
{
insert(nod->left,val);
}
else if(nod->data < val)
{
insert(nod->right,val);
}
}
相关文章:
- 这是一个二叉搜索树吗?黑客排名问题
- 插入操作的二叉搜索树代码问题
- 我的模板二叉搜索树类给出了错误"Node<T>: no appropriate default constructor available,"如何解决这个问题?
- 如何使用二叉搜索树的索引生成器解决此问题
- 错误 C2676;在C++的二叉搜索树类中定义 ++ 运算符时遇到问题
- 在二叉搜索树中插入时出现问题
- 二叉搜索树插入数据问题
- 二叉搜索树析构函数问题
- 我的二叉搜索树插入逻辑有什么问题?
- 二叉搜索树在插入功能方面有问题
- 模板二叉搜索树 ostream 过载问题
- 平衡的二叉搜索树问题
- 二叉搜索树:搜索功能问题
- C++二进制搜索树删除问题
- C++二进制搜索树切换语句问题
- 创建二进制搜索树时出现分段故障问题
- 以下插入 c++ 二叉搜索树的代码有什么问题
- 二叉搜索树问题和数据结构问题
- 二进制搜索树问题
- 二进制搜索树显示问题