c之二叉樹鏈表操作---建立、(遞迴)前序走訪、中序遍曆、後序遍曆

來源:互聯網
上載者:User

標籤: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之二叉樹鏈表操作---建立、(遞迴)前序走訪、中序遍曆、後序遍曆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.