二叉樹的其他操作

    之前實現過二叉樹的創建,非遞歸遍歷和遞歸遍歷。現在添加一些其他的操作,包括:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章