生成N个节点随机二叉查找树的函数 具有从1到N的不同的关键字

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