码迷,mamicode.com
首页 > 其他好文 > 详细

c之二叉树链表操作---建立、(递归)前序遍历、中序遍历、后序遍历

时间:2014-11-27 20:37:04      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:c语言

【二叉树链表】bubuko.com,布布扣

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之二叉树链表操作---建立、(递归)前序遍历、中序遍历、后序遍历

标签:c语言

原文地址:http://blog.csdn.net/mycodequeen/article/details/41549127

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!