美文网首页
c语言-二叉树

c语言-二叉树

作者: 遇银 | 来源:发表于2020-04-26 17:28 被阅读0次
#include <stdio.h>
#include <stdlib.h>

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

//插入节点
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);
}

运行结果:

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

相关文章

  • 算法与数据结构系列之[二叉树-中]

    上篇介绍了二叉树的理论部分,这篇贴出二叉树完整的C语言代码实现。 BinaryTree.c BinaryTree....

  • 算法与数据结构系列之[二叉树-下]

    上篇贴出了二叉树的C语言代码实现,这篇贴出Java代码实现。

  • 经典算法代码集

    本文是经典算法的集合,使用C#语言来实现。 1. 二叉树 二叉树结构定义 1.1 二叉树的遍历 先定义一个遍历处理...

  • c语言-二叉树

    运行结果:

  • 2018-11-19

    今天在电脑上用c语言实现了二叉树的创建,并且采用递归算法的形式进行二叉树的先序遍历和中序遍历以及后序遍历。

  • C语言_typedef、union

    @(C语言) [toc] typedef 作用 设置别名,并没有创建新的类型 使用 定义一个二叉树: 现在可以写成...

  • C++简答题

    一、简答题 1、C语言与C++语言的区别? 答: C语言是面向过程语言,C++是面向对象语言(OOP) C语言...

  • 二叉树操作的C++实现

    这几天做数据结构的作业,苦于C++没有现成的二叉树的类,书本上的实现方法是c语言的,而且一点都不好看,太郁闷了。 ...

  • C语言快速入门 - Hello World 详解

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

  • C语言快速入门 - 简单运算符

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

网友评论

      本文标题:c语言-二叉树

      本文链接:https://www.haomeiwen.com/subject/ajejwhtx.html