c語言-二叉樹

#include <stdio.h>
#include <stdlib.h>

typedef struct binary_tree
{
    int data;
    struct binary_tree *left;
    struct binary_tree *right;
}node;

//插入節(jié)點(diǎn)
void insert(node **tree,int val)
{
    node *temp = NULL;
    if(!(*tree))
    {
        temp = (node *)malloc(sizeof(node));
        temp->left =temp->right =NULL;
        temp->data = val;
        *tree = temp;
        return ;
    }

    if(val<(*tree)->data)
    {
        insert(&(*tree)->left,val);
    }
    else
    {
        insert(&(*tree)->right,val);
    }

}
//回收資源
void deltree(node *tree)
{
    if(tree)
    {
        deltree(tree->left);
        deltree(tree->right);
        free(tree);
    }
}

//先序
void print_preorder(node *tree)
{
    if(tree)
    {
        printf("%d\n",tree->data);
        print_preorder(tree->left);
        print_preorder(tree->right);
    }
}
//中序
void print_inorder(node *tree)
{
    if(tree)
    {
        print_inorder(tree->left);
        printf("%d\n",tree->data);
        print_inorder(tree->right);
    }
}
//后序
void print_postorder(node *tree)
{
    if(tree)
    {
        print_postorder(tree->left);
        print_postorder(tree->right);
        printf("%d\n",tree->data);
    }
}

int _max(int a, int b)
{
    return a>b?a:b;
}
//最大深度
int maxDepth(node *tree)
{
    if(tree == NULL)
    {
        return 0;
    }
    return 1+ _max(maxDepth(tree->left),maxDepth(tree->right));
}
//test
int main(void)
{
    node *root;
    root = NULL;

    insert(&root,9);
    insert(&root,4);
    insert(&root,15);
    insert(&root,6);
    insert(&root,12);
    insert(&root,17);
    insert(&root,2);

    printf("Pre Order Didplay\n");
    print_preorder(root);

    printf("In Order Display\n");
    print_inorder(root);

    printf("Post Order Display\n");
    print_postorder(root);

    printf("maxdepth= %d\n",maxDepth(root));

    deltree(root);
}

運(yùn)行結(jié)果:

wa@ubuntu:~$ gcc tree.c -o tree
wa@ubuntu:~$ 
wa@ubuntu:~$ 
wa@ubuntu:~$ ./tree
Pre Order Didplay
9
4
2
6
15
12
17
In Order Display
2
4
6
9
12
15
17
Post Order Display
2
6
4
12
17
15
9
maxdepth= 3
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容