【发布时间】:2017-01-24 18:44:07
【问题描述】:
我尝试如下实现 BST .创建结构为NODE。它有两个指针左右和一个整数值(数据)。
#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设置为节点。将ptr设置为nodes不会更改父级的left或right指针。
标签: c++ linked-list binary-search-tree