標籤:c語言
【二叉樹鏈表】
1.節點定義:
typedef struct node{
int data;
struct node*lchild,*rchild;
}Tree,*BiTree;
2.建立二叉樹:
BiTree creat_Tree(BiTree root,int num){//建立二叉樹
if(root==NULL)
{
root=(Tree *)malloc(sizeof(Tree));
if(root==NULL)
{
printf("no memory available\n");
return NULL;
}
root->data=num;
root->lchild=NULL;
root->rchild=NULL;
}
else
{
if(num < root->data)
root->lchild=creat_Tree(root->lchild,num);
else
root->rchild=creat_Tree(root->rchild,num);
}
return root;
}
下面是對二叉樹的遍曆問題,由於初學唯寫了遞迴的遍曆,還沒有研究非遞迴的遍曆
3.先序遍曆二叉樹,遍曆順序為,根、左、右
void pre_order(BiTree root){
if(root==NULL)
return;
printf("%d\t",root->data);
pre_order(root->rchild);
pre_order(root->lchild);
}
4.中序遍曆二叉樹,遍曆順序為,左、中、右
void in_order(BiTree root){
if(root==NULL)
return ;
in_order(root->rchild);
printf("%d\t",root->data);
in_order(root->lchild);
}
5.後序遍曆二叉樹,遍曆順序為,左、右、中8
void post_order(BiTree root){
if(root==NULL)
return ;
post_order(root->rchild);
post_order(root->lchild);
printf("%d\t",root->data);
}
6.函數主體部分
int main()
{
int n,num;
BiTree root=NULL;
printf("please imput the total number of tree:\n");
scanf("%d",&n);
while(n--){
printf("please input the num of insert:\n");
scanf("%d",&num);
root=creat_Tree(root,num);
}
printf("please choice the traversal mean:\n1--pre_order\n2--in_order\n3--post_order\n");
int choice;
scanf("%d",&choice);
switch(choice){
case 1:
pre_order(root);
break;
case 2:
in_order(root);
break;
case 3:
post_order(root);
break;
}
return 0;
}
c之二叉樹鏈表操作---建立、(遞迴)前序走訪、中序遍曆、後序遍曆