#include
#include
/*
遞歸前中后遍歷
*/
typedef struct node
{
int data;
struct node*left;
struct node*right;
}BTnode;
BTnode*CreateTree(int a[],int n)
{
BTnode*root,*c,*p,*pa;
int i;
root=(BTnode*)malloc(sizeof(BTnode));
root->data=a[0];
root->left=root->right=NULL;//建立根節(jié)點
for(i=1;idata=a[i];
p->left=p->right=NULL;
c=root; //根節(jié)點給C指針
while(c){ //判斷p結(jié)點時屬于左子樹還是右子樹
pa=c; //pa指針是p結(jié)點的父節(jié)點
if(c->data>p->data)
c=c->left;
else //如果結(jié)點值右重復,則后面結(jié)點在右孩子上
c=c->right;
}
if(pa->data>p->data) //p結(jié)點時父節(jié)點的左孩子還是右孩子
pa->left=p;
else
pa->right=p;
}
return root;
}
void Forder(BTnode*root){
if(root){
printf("%d",root->data);
printf("\n");
Forder(root->left);
Forder(root->right);
}
}
void Inorder(BTnode*root){
if(root){
Inorder(root->left);
printf("%3d",root->data);
printf("\n");
Inorder(root->right);
}
}
void Porder(BTnode*root){
if(root){
Porder(root->left);
Porder(root->right);
printf("%6d",root->data);
printf("\n");
}
}
int main(void){
BTnode*root;
int *a;
int n;
int i;
printf("請輸入n=");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
printf("請輸入數(shù)組a[]=");
for(i=0;i
文章標題:二叉排序樹創(chuàng)建(數(shù)組)
當前網(wǎng)址:http://weahome.cn/article/ppdphg.html