您好,登錄后才能下訂單哦!
本篇文章為大家展示了二叉樹的操作有哪些呢,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
之前實現(xiàn)過二叉樹的創(chuàng)建,非遞歸遍歷和遞歸遍歷。現(xiàn)在添加一些其他的操作,包括:
銷毀一棵樹
計算樹的深度(高度)
.計算葉子節(jié)點的個數(shù)
計算所有節(jié)點的個數(shù)
復(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è)資訊頻道。
免責(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)容。