二叉搜索树插入(c++)
insertion in binary search tree (C++)
我是数据结构新手。我在做一个c++程序插入一个元素在二叉搜索树。程序编译没有任何错误,但当我运行程序时,在输入第一个n后,程序停止工作。请帮助我使这个程序正常工作。
我的代码如下:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node *root=NULL ,*par=NULL ,*pos=NULL,*save=NULL , *ptr=NULL ;
struct node* newNode(int data)
{
struct node* newnode= (struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->right=NULL;
newnode->left=NULL;
return newnode;
}
void findpos(int data)
{
if(root==NULL)
{
par=NULL,pos=NULL;
return;
}
if(root->data==data)
{
par=NULL , pos=root;
return;
}
if(data<root->data)
{
save=root; ptr=root->left;
}
else{
save=root; ptr=root->right;
}
while(ptr!=NULL)
{
if(ptr->data==data)
{
par=save; pos=ptr;
return;
}
if(data<ptr->data)
{
save=ptr;
ptr=ptr->left;
}
else{
save=ptr;
ptr=ptr->right;
}
}
pos=NULL; par=save;
return;
}
void insert(int data)
{
findpos(data);
if(pos!=NULL)
{
return;
}
pos=newNode(data);
if(data<par->data)
par->left=pos;
else
par->right=pos;
return;
}
int main()
{
struct node *root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}
main()中声明的根指针覆盖全局根指针。然后在第一次findpos()时,根(全局)仍然为NULL。因此,只需替换该代码:
int main()
{
struct node *root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}
By this:
int main()
{
root= newNode(4);
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
int n;
cin>>n;
insert(n);
cout<<pos->data; //just trying to see if it works
return 0;
}
修改main方法,使其在全局命名空间中修改root;在main
中声明一个名为root
local的新节点之前。
int main() {
// struct node *root = newNode(4); // you made this root a member of main.
// not a global member anymore.
root = newNode(4); // use this
// Populate some nodes
root->left=newNode(3);
root->left->left=newNode(2);
root->right=newNode(6);
/* tree so far:
* 4
* /
* 3 6
* /
* 2
*/
int n;
cin >> n;
cout << "user input " << n << "n";
insert(n);
cout << pos->data; //just trying to see if it works
return 0;
}
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 将重物插入std::map
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 在数字之间插入 + 或 - 符号以使其等于整数
- 在字符串中插入空格
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?