数据结构与算法分析——c语言描述 练习4.29
本来想用一个长度为N的数组记录是否生成过这个随机数,然后在插入到树中。
看了作者的给的代码瞬间惊讶。还能这样做。
#include"fatal.h"
#include<stdlib.h>
typedef int ElementType;
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
struct TreeNode {
ElementType element;
SearchTree left;
SearchTree right;
};
int RandInt(int i, int j) {
int temp;
temp = i + (1.0*rand() / RAND_MAX)*(j - i);
return temp;
}
SearchTree makeRandomTree1(int lower, int upper) {
if (lower <= upper) {
SearchTree t;
int randomNum = RandInt(lower, upper);
t = malloc(sizeof(struct TreeNode));
if (t == NULL)
Error("OUT OF MEMORY");
t->element = randomNum;
t->left=makeRandomTree1(lower, randomNum - 1);
t->right = makeRandomTree1(randomNum + 1, upper);
return t;
}
return NULL;
}
SearchTree makeRandomTree(int n) {
return makeRandomTree1(1, n);
}
void dir(SearchTree t) {
if (t) {
printf("%d ", t->element);
dir(t->left);
dir(t->right);
}
}
int main() {
SearchTree t = makeRandomTree(90);
dir(t);
}