数据结构与算法分析生成N节点随机二叉查找树

来源:互联网 发布:鬼真实存在吗 知乎 编辑:程序博客网 时间:2024/05/21 07:56
/*生成n节点随机二叉查找树,该树具有从1到n的不同关键字*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *Position;
typedef struct Node *Tree;
Tree makeRandomTree(int lower,int upper);
void printTree(Tree T);
int RandInt(int i,int j);
struct Node{
    int element;
    Tree Left;
    Tree Right;
};
int RandInt(int i,int j)//生成一个i到j之间的值。
{
    int temp;
    temp=i+(1.0*rand()/RAND_MAX)*(j-i);
    return temp;
}
Tree makeRandomTree(int lower,int upper)//建立一个随机树
{
    if(lower<=upper)
    {
    int num=RandInt(lower,upper);
    Tree t;
    t=(Tree)malloc(sizeof(struct Node));
    if(t==NULL)
    {    printf("error");
        return NULL;
    }
    t->element=num;
    t->Left=makeRandomTree(lower,num-1);
    t->Right=makeRandomTree(num+1,upper);
    return t;
    }
    return NULL;

}
void printTree(Tree T)//前序遍历打印树
{
    if(T!=NULL)
    {
        printf("%d",T->element);
        printTree(T->Left);
        printTree(T->Right);
    }
}
main()
{
    Tree t;
    t=makeRandomTree(1,10);
    printTree(t);
}
阅读全文
0 0
原创粉丝点击