Random 基于rand的二叉搜索树

Random 基于rand的二叉搜索树,random,binary-tree,Random,Binary Tree,我正在尝试创建一个包含50个随机变量的二叉搜索树,我写了一个代码,但是没有声明随机变量。请帮助我 #include <iostream> #include <cstdlib> using namespace std; #包括 #包括 使用名称空间std; //创建一个包含值的类节点,rvalue存储rlink指向的值,Levalue存储llink指向的值 class node { private: int value; int rvalue; int lvalue

我正在尝试创建一个包含50个随机变量的二叉搜索树,我写了一个代码,但是没有声明随机变量。请帮助我

#include <iostream>
#include <cstdlib>
using namespace std;
#包括
#包括
使用名称空间std;
//创建一个包含值的类节点,rvalue存储rlink指向的值,Levalue存储llink指向的值

class node


{
private:
int value;
int rvalue;
int lvalue;
node *rlink;
node *llink;

public:

void insertnode(node*,int);
node *create(node*,int); 

};



void node::insertnode(node *h,int k)

{

h=new node;
h->value=k;
h->rlink=NULL;
h->llink=NULL;
h->rvalue=0;
h->lvalue=0;

}


node *node::create(node*root, int i)

{

int A[i];
for(int j=0; j<i; j++) {
    A[j]=rand()%1000;  //stores random values in array
    cout<<A[j];

}
node *k;
node *h;
insertnode(root, A[0]);

cout<<h->value;

for (int j=1; j<i; j++) {
    if(A[j]<h->value){
        if(h->llink==NULL) {
            insertnode(k, A[j]);
            h->lvalue=k->value;

        }
        h->llink=k;
    }
    else if(A[j]>h->value)
    {
        if(h->rlink==NULL) {
            insertnode(k, A[j]);
            h->rvalue=k->value;

        }
        h->rlink=k;

    }


} 

return root;


}


int main()

{


int i;
cout<<"enter the number of elements in a matix";
cin>>i;
node s;
node *h;
h=s.create(h,i);

}
类节点
{
私人:
int值;
int-rvalue;
int左值;
节点*rlink;
节点*llink;
公众:
void insertnode(node*,int);
节点*创建(节点*,int);
};
void node::insertnode(node*h,int k)
{
h=新节点;
h->值=k;
h->rlink=NULL;
h->llink=NULL;
h->R值=0;
h->左值=0;
}
节点*节点::创建(节点*根,int i)
{
int A[i];
对于(int j=0;jh->value)
{
如果(h->rlink==NULL){
insertnode(k,A[j]);
h->R值=k->值;
}
h->rlink=k;
}
} 
返回根;
}
int main()
{
int i;
库蒂;
节点s;
节点*h;
h=s.create(h,i);
}

在函数create()中,您使用的是变量k和h,它们是指向节点的指针。但是您还没有初始化这些变量,也没有为这些指针分配空间。首先为这些变量分配内存。

您的代码有很多问题

  • 要创建节点,只需为给定值创建一个新节点(这应该通过构造函数完成。节点类中的其他值将在节点插入到树中时初始化)
  • 要插入节点,您应该始终传递树的根(或对树本身的引用)和要插入的节点,然后在insert方法中找到插入节点的位置(如有必要,也可以在此处执行任何平衡)
  • 如果使用树方法(我建议使用树方法),那么树应该有一个对其根的引用,可能还有一个节点计数
  • 要生成随机节点,使用数组没有任何用处,您只需获取一个新的随机值,为其创建一个节点,然后将其插入列表中即可
要完成本文的最后一部分,请执行以下操作(假设为C++)

int main(){
Tree*Tree=new Tree();//这将创建一个树(您需要使用构造函数创建一个树类
int total=50;//这是要存储的节点数,但这是必需的
....
srand(时间(空));
对于(int i=0;i

这将创建一个树,具有50个值,假设节点和树的构造函数和插入节点方法词

,你应该用相关语言(C或C++假设)来标记你的问题。
int main() { 
  Tree *tree = new Tree(); //This creates a tree (you will need to create a tree class with a constructor
  int total = 50; //This the number of nodes you want store this however is necessary
  ....
  srand(time(NULL));
  for(int i = 0; i < total; i++) {
     int val = rand() % 1000 + 1; //This gets a number between 1-1000
     Node *node = new Node(val); //This constructs the node (write this constructor)
     tree.insertNode(node); //This will insert the node into the tree (write this method)
  }
  ....
}