使用rand的二叉搜索树

时间:2012-04-10 16:40:32

标签: random binary-tree

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

#include <iostream>
#include <cstdlib>
using namespace std;

//创建一个包含值的类节点,rvalue存储rlink指向的值,而lvalue存储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);

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您的代码存在很多问题。

  • 要创建节点,只需为给定值创建一个新节点(这应该使用构造函数完成。当节点插入树中时,将初始化节点类中的其他值)
  • 要插入节点,您应该始终传递树的根(或对树本身的引用)和要插入的节点,然后在insert方法中找到插入节点的位置(这也可以是您的位置如有必要,做一个平衡的事情)
  • 如果您使用树方法(我建议),树应该引用它的根,可能还有一个节点的计数
  • 要生成随机节点,使用数组是没有用的,您应该只获取一个新的随机值,为它创建一个节点,并将其插入列表中

要做到这一点的最后一部分(假设是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)
  }
  ....
}

这将创建一个具有50个值的树,假设Node和Tree的构造函数和insertNode方法单词

相关问题