#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct TreeNode *SearchTree;
struct TreeNode{
SearchTree Left;
SearchTree Right;
int Element;
};
//类似于中序遍历 不过是中序赋值罢了
SearchTree GenTree( int Height, int *LastNode ) //构造 高度一定时节点数最小的二叉树
{
SearchTree T;
if( Height >= 0 ){
T = (SearchTree)malloc(sizeof(struct TreeNode));
T->Left = GenTree( Height - 1, LastNode );
T->Element = ++*LastNode;
T->Right = GenTree( Height - 2, LastNode ); //改为 Height-1即是完美二叉树
return T;
}
else //为什么不能用 T = NULL 而是 必须要返回
return NULL;
}
SearchTree MinAvlTree(int H)
{
int LastNodeAssigned = 0;
return GenTree( H, &LastNodeAssigned );
}
void PreTrv(SearchTree T)//先序遍历
{
if(T){
printf("%d ",T->Element);
PreTrv(T->Left);
PreTrv(T->Right);
}
}
void InTrv(SearchTree T)//中序遍历
{
if(T){
InTrv(T->Left);
printf("%d ",T->Element);
InTrv(T->Right);
}
}
int RanInt(int L, int U)
{
srand((unsigned)time(NULL));
return rand()%(U-L+1)+L;
}
SearchTree MakeRandomTree1( int Lower, int Upper )
{
SearchTree T;
int RandomValue;
T = NULL;
if( Lower <= Upper ){
T = (SearchTree)malloc(sizeof(struct TreeNode));
T->Element = RandomValue = RanInt(Lower, Upper);
T->Left = MakeRandomTree1(Lower, RandomValue-1);
T->Right = MakeRandomTree1(RandomValue+1, Upper);
}
return T;
}
SearchTree MakeRandomTree(int N)
{
return MakeRandomTree1(1, N);
}
int main()
{
// int H;
SearchTree T1,T2;
// scanf("%d",&H);
// T1 = MinAvlTree(H);
int N;
// printf("%d",RanInt(1,10));
scanf("%d",&N);
T2 = MakeRandomTree(N);
printf("\n先序遍历 :\n\t");
PreTrv(T2);
// printf("\n中序遍历 : \n\t");
// InTrv(T2);
return 0;
}
构建最少节点的AVL树~
原文作者:AVL树
原文地址: https://blog.csdn.net/Tianweidadada/article/details/76557711
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/Tianweidadada/article/details/76557711
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。