C語言實現(xiàn)二叉鏈表存儲
更新時間:2018年08月18日 09:17:34 作者:data_heng
這篇文章主要為大家詳細介紹了C語言實現(xiàn)二叉鏈表存儲的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
利用二叉鏈表存儲,并且利用遞歸的方法實現(xiàn)二叉樹的遍歷(前序遍歷、中序遍歷和后續(xù)遍歷)操作。
c語言具體實現(xiàn)代碼如下:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef int ElemType;//數(shù)據(jù)類型 //定義二叉樹結構,與單鏈表相似,多了一個右孩子結點 typedef struct BiTNode { ElemType data; struct BiTNode *lChild,*rChild; }BiTNode,*BiTree; //先序創(chuàng)建二叉樹 int CreateBiTree(BiTree *T) { ElemType ch; ElemType temp; scanf("%d",&ch); temp=getchar(); if(ch==-1) { *T=NULL; } else { *T=(BiTree)malloc(sizeof(BiTNode)); if(!(*T)) { exit(-1); } (*T)->data=ch; printf("輸入%d的左子結點:",ch); CreateBiTree(&(*T)->lChild); printf("輸入%d的右子結點:",ch); CreateBiTree(&(*T)->rChild); } return 1; } //先序遍歷二叉樹 void TraverseBiTree(BiTree T) { if(T==NULL) { return; } printf("%d",T->data); TraverseBiTree(T->lChild); TraverseBiTree(T->rChild); } //中序遍歷二叉樹 void InOrderBiTree(BiTree T) { if(T==NULL) { return; } InOrderBiTree(T->lChild); printf("%d",T->data); InOrderBiTree(T->rChild); } //后序遍歷二叉樹 void PostOrderBiTree(BiTree T) { if(T==NULL) { return; } PostOrderBiTree(T->lChild); PostOrderBiTree(T->rChild); printf("%d",T->data); } //二叉樹的深度 int TreeDeep(BiTree T) { int deep=0; if(T) { int leftdeep=TreeDeep(T->lChild); int rightdeep=TreeDeep(T->rChild); deep=leftdeep>=rightdeep?leftdeep+1:rightdeep+1; } return deep; } //求二叉樹葉子結點個數(shù) int Leafcount(BiTree T,int &num) { if(T) { if(T->lChild==NULL&&T->rChild==NULL) { num++; } Leafcount(T->lChild,num); Leafcount(T->rChild,num); } return num; } //主函數(shù) int main(void) { BiTree T; BiTree *p=(BiTree *)malloc(sizeof(BiTree)); int deepth,num=0; printf("請輸入第一個結點的值,-1表示沒有葉結點:\n"); CreateBiTree(&T); printf("先序遍歷二叉樹:\n"); TraverseBiTree(T); printf("\n"); printf("中序遍歷二叉樹:\n"); InOrderBiTree(T); printf("\n"); printf("后序遍歷二叉樹:\n"); PostOrderBiTree(T); printf("\n"); deepth=TreeDeep(T); printf("數(shù)的深度為:%d",deepth); printf("\n"); Leafcount(T,num); printf("數(shù)的葉子結點個數(shù)為:%d",num); printf("\n"); return 0; }
得到的結果如下圖所示:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Matlab利用隨機森林(RF)算法實現(xiàn)回歸預測詳解
這篇文章主要為大家詳細介紹了Matlab如何利用隨機森林(RF)算法實現(xiàn)回歸預測,以及自變量重要性排序的操作,感興趣的小伙伴可以了解一下2023-02-02