数据结构与算法分析——c语言描述 练习4.30
挺有意思的。用了4.16练习的结论。递推与递归结合,生成一颗随机avl树
#include"fatal.h"
#include<stdlib.h>
typedef int ElementType;
struct AvlNode;
typedef struct AvlNode *Position;
typedef struct AvlNode *AvlTree;
struct AvlNode {
ElementType element;
AvlTree left;
AvlTree right;
int isDeleted;
int height;
};
int RandInt(int i, int j) {
int temp;
temp = (int)(i + (1.0*rand() / RAND_MAX)*(j - i));
return temp;
}
AvlTree makeRandomAVLTree(int H) {
if (H >= 0) {
AvlTree t = malloc(sizeof(struct AvlNode));
if (t == NULL)
Error("OUT OF MEMORY");
t->left = makeRandomAVLTree(H - 1);
t->right = makeRandomAVLTree(H - 2);
if (t->left == NULL&&t->right == NULL) {
t->element = rand();
}
else if (t->left == NULL)
t->element = RandInt(0, t->right->element);
else if (t->right == NULL)
t->element = RandInt(t->left->element, RAND_MAX);
else
t->element = RandInt(t->left->element, t->right->element);
return t;
}
return NULL;
}
void dir(AvlTree t) {
if (t) {
printf("%d ", t->element);
dir(t->left);
dir(t->right);
}
}
int main() {
AvlTree t = makeRandomAVLTree(9);
dir(t);
}