生成具有最少节点、高度为H的AVL树的程序

数据结构与算法分析——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);
}
    原文作者:AVL树
    原文地址: https://blog.csdn.net/qq789045/article/details/51228457
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞