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

二叉树的其他操作

时间:2016-07-13 06:58:32      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:include   二叉树   return   叶子   

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

  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;
}


本文出自 “君峰俊宇” 博客,请务必保留此出处http://10274409.blog.51cto.com/10264409/1825894

二叉树的其他操作

标签:include   二叉树   return   叶子   

原文地址:http://10274409.blog.51cto.com/10264409/1825894

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