溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

二叉樹的操作有哪些呢

發(fā)布時間:2021-11-25 15:29:18 來源:億速云 閱讀:125 作者:柒染 欄目:編程語言

本篇文章為大家展示了二叉樹的操作有哪些呢,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

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

  1. 銷毀一棵樹

  2. 計算樹的深度(高度)

  3. .計算葉子節(jié)點的個數(shù)

  4. 計算所有節(jié)點的個數(shù)

  5. 復(fù)制二叉樹   

具體見代碼:

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node* lchild;
    struct Node* rchild;
}Node;
//創(chuàng)建樹
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;
}
//計算葉子節(jié)點的個數(shù)
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);
    }
}
//計算所有節(jié)點的個數(shù)
int count_all_node(Node* root)
{
    if(root==NULL)
    {
        return 0;
    }
    return count_all_node(root->lchild)+count_all_node(root->rchild)+1;
}
//復(fù)制二叉樹
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;
}

上述內(nèi)容就是二叉樹的操作有哪些呢,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI