【二叉树链表】
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;
}