一、原理
运用冒泡排序预处理数组。运用递归,搜索是否元素已经存在,若不存在就创建新节点,将数据写入。最后运用递归实现二叉树的中序遍历测试二叉树是否创建成功。
二、代码实现
#include "stdio.h"
#include "stdlib.h"
#define len 10
typedef struct Node{
int data;
struct Node *left;
struct Node *right;
}Node;
void order(int array[]){
int tag=0; //用于冒泡排序算法优化;
for(int i=0;i<len;i++){
for(int j=0;j<len-i-1;j++){
if(array[j]>array[j+1]){
tag=1;//标记元素发生交换;
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}//元素交换;
}//冒泡排序;
if(tag==0){
break;
}//未发生元素交换,原数组有序,排序提前结束;
}
}//用于优化树(冒泡排序);
Node *Write(int data){
Node *New=(Node *)malloc(sizeof(Node));//分配内存;
New->data =data;//写入数据;
New->left=NULL;
New->right=NULL;//节点初始化;
return New;//返回新节点;
}//创建新节点,写入数据;
void Tree_grow(Node *root,int data){
if(root->data<data){//处理左子树;
if(root->left==NULL){//未找到数据,增加左子树;
root->left=Write(data);
}else{//未找到数据,继续向左递归搜索;
Tree_grow(root->left,data);
}
}else if(root->data>data){//处理右子树;
if(root->right==NULL){//未找到数据,增加右子树;
root->right=Write(data);
}else{//未找到数据,继续向右递归搜索;
Tree_grow(root->right,data);
}
}else if(root->data==data){//数据已存在;
printf("The element is already there!\n");
}
}
void Output(Node *root){
if(root!=NULL){
Output(root->left);
printf("%d\n",root->data);
Output(root->right);
}
}//树的遍历输出(中序遍历);
int main(void){
int array[]={5,4,6,3,7,2,8,1,9};//原始数组;
Node *root=Write(array[0]);//初始化根节点;
order(array);//排序,用于优化二叉树;
for(int i=1;i<len/2;i++){
Tree_grow(root,array[len/2-i]);
Tree_grow(root,array[len/2+i]);
}//数据写入;
Output(root);//测试
return 0;
}