通过结构实现BST

BST implementation through structure

本文关键字:BST 实现 结构      更新时间:2023-10-16

>我尝试按如下方式实现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,但实际上您应该将父级的leftright设置为nodes。将ptr设置为 nodes 不会更改父级的leftright指针。

所以做这样的事情:

{
    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;
        }
    }
}

注意:上面的代码没有经过测试,但描述了该方法。