通过结构实现BST
BST implementation through structure
>我尝试按如下方式实现BST.创建的结构为 NODE.it 有两个左右指针和一个整数值(数据)。
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
struct node*left;
struct node*right;
int data;
};
node* head1;
int bol=0;
void insert1(int x)
{
node* nodes=new node;
nodes->left=NULL;
nodes->right=NULL;
nodes->data=x;
if(bol==0)
{
head1=nodes;
bol=1;
}
else
{
node* ptr=head1;
while(ptr!=NULL)
{
if(x<=ptr->data)
{
ptr=ptr->left;
}
else
{
ptr=ptr->right;
}
}
ptr=nodes;
}
}
int main()
{
int n,m;
cout<<"Enter the size of first BST"<<endl;
cin>>n;
int arrayfirst[n];
for(int i=0;i<n;i++)
{
cin>>arrayfirst[i];
insert1(arrayfirst[i]);
}
cout<<head1->data<<endl;
cout<<head1->left->data<<endl;
//printPreorder(head1);
}
但是,如果我尝试打印下一个节点到头部的数据,则会显示错误。
提前致谢
您正在设置ptr = nodes
,但实际上您应该将父级的left
或right
设置为nodes
。将ptr
设置为 nodes
不会更改父级的left
或right
指针。
所以做这样的事情:
{
node* ptr=head1;
node *parent = NULL;
while(ptr != NULL) {
parent = ptr;
if(x <= ptr->data) {
ptr = ptr->left;
}
else {
ptr = ptr->right;
}
}
if (parent != NULL) { // this should always be true
if (parent->left == ptr) {
parent->left = nodes;
} else {
parent->right = nodes;
}
}
}
注意:上面的代码没有经过测试,但描述了该方法。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 实现 BST 时出现分段错误
- 在我的 BST 实现中,我的 findNode 函数没有将父位置返回给其调用函数
- 试图实现BST时,将C 的分割故障(核心倾倒)
- 通过结构实现BST
- 通过数组实现BST,通过链表实现堆
- 使用 BST 实现队列
- 我的bst实现出了什么问题
- STL中的BST实现