数据结构与算法分析——c语言描述 练习4.33 答案
只是计算完坐标,还没写展示。有空在把展示写了。
#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 x;
int y;
};
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);
t->height = H;
return t;
}
return NULL;
}
void calcX(AvlTree t, int *lastX) {
if (t) {
calcX(t->left, lastX);
t->x = (++*lastX);
calcX(t->right, lastX);
}
}
void calcY(AvlTree t,int TreeHeight){
if (t) {
t->y = TreeHeight- t->height;
calcY(t->left,TreeHeight);
calcY(t->right,TreeHeight);
}
}
void CalculateCoordinates(AvlTree t) {
int x = 0;
calcX(t, &x);
calcY(t,t->height);
}
void dir(AvlTree t) {
if (t) {
fprintf(stderr, "%d x:%d y: %d\n",t->element, t->x,t->y);
dir(t->left);
dir(t->right);
}
}
int main() {
AvlTree t = makeRandomAVLTree(3);
CalculateCoordinates(t);
dir(t);
}