生成一颗具有关键字从1到2^(H+1)-1且高为H的理想平衡二叉树

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