数据结构与算法分析——c语言描述 练习4.31 答案
和生成随机二叉树差不多,只不过递归调用的时候左右子树高度均为H-1
#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;
};
SearchTree GenTree(int H, int *lastNodeElem) {
if (H >= 0) {
SearchTree t = malloc(sizeof(struct TreeNode));
if (t == NULL)
Error("OUT OF MEMORY");
t->left = GenTree(H - 1, lastNodeElem);
t->element = ++*lastNodeElem;
t->right = GenTree(H - 1, lastNodeElem);
return t;
}
return NULL;
}
SearchTree makePerfectTree(int H) {
int lastElem = 0;
return GenTree(H, &lastElem);
}
void dir(SearchTree t) {
if (t) {
printf("%d ", t->element);
dir(t->left);
dir(t->right);
}
}
int main() {
SearchTree t = makePerfectTree(2);
printf("%d", t->right->element);
}