温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

二叉树的操作有哪些呢

发布时间:2021-11-25 15:29:18 来源:亿速云 阅读:120 作者:柒染 栏目:编程语言

本篇文章为大家展示了二叉树的操作有哪些呢,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

    之前实现过二叉树的创建,非递归遍历和递归遍历。现在添加一些其他的操作,包括:

  1. 销毁一棵树

  2. 计算树的深度(高度)

  3. .计算叶子节点的个数

  4. 计算所有节点的个数

  5. 复制二叉树   

具体见代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node* lchild;
    struct Node* rchild;
}Node;
//创建树
Node* create_tree()
{
    int _data;
    scanf("%d",&_data);
    if(_data==100)
    {
        return NULL;
    }
    Node* root=(Node*)malloc(1*sizeof(Node));
    if(root==NULL)
    {
        return ;
    }
    root->data=_data;
    root->lchild=create_tree();
    root->rchild=create_tree();
    return root;
}
// 前序遍历
void pre_print(Node* root)
{
    if(root==NULL)
    {
        return ;
    }
    printf("%d\t",root->data);
    pre_print(root->lchild);
    pre_print(root->rchild);
}
/****************************************************/
//销毁一棵树
void free_tree(Node* root)
{
    if(root==NULL)
        return ;
    free_tree(root->lchild);
    free_tree(root->rchild);
    free(root);
    root=NULL;
}
//计算树的深度(高度)
int depth(Node* root)
{
    if(root==NULL)
        return 0;
    int l=depth(root->lchild);
    int r=depth(root->rchild);
    if(l>r)
    {
        return l+1;
    }
    return r+1;
}
//计算叶子节点的个数
int count_leaf(Node* root)
{
    if(root==NULL)
    {
        return 0;
    }
    if(root->lchild==NULL && root->rchild==NULL)
    {
        return 1;
    }
    else
    {
        return count_leaf(root->lchild)+count_leaf(root->rchild);
    }
}
//计算所有节点的个数
int count_all_node(Node* root)
{
    if(root==NULL)
    {
        return 0;
    }
    return count_all_node(root->lchild)+count_all_node(root->rchild)+1;
}
//复制二叉树
Node* copy_tree(Node* root)
{
    if(root==NULL)
    {
        return NULL;
    }
    Node* l_tree,*r_tree,*root_tree;
    l_tree=copy_tree(root->lchild);
    r_tree=copy_tree(root->rchild);
    root_tree=malloc(1*sizeof(Node));
    root_tree->data=root->data;
    root_tree->lchild=l_tree;
    root_tree->rchild=r_tree;
    return root_tree;
}
int main(int argc, char const *argv[])
{
    Node* root=create_tree();
    pre_print(root);
    printf("\n");
    printf("Depth:%d\n",depth(root));
    printf("count_leaf:%d\n",count_leaf(root));
    printf("count_all_node:%d\n",count_all_node(root));
    Node* copy_root=copy_tree(root);
    pre_print(root);
    printf("\n");
    return 0;
}

上述内容就是二叉树的操作有哪些呢,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI