日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

树:求二叉树的高度和叶子结点数量

發布時間:2025/3/15 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 树:求二叉树的高度和叶子结点数量 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

算法代碼很簡單都是用使用遞歸計算,大家把遞歸思想領悟到就ok了

二叉樹高度算法

//求二叉樹的高度 采用遞歸的方式 void GetHeight(BiTree tree, int* heightNum) {if (NULL != tree){int LHeight;int RHight;GetHeight(tree->lchild,&LHeight);GetHeight(tree->rchild,&RHight);*heightNum = LHeight > RHight ? LHeight + 1 : RHight + 1;}else{*heightNum = 0;} }


二叉樹葉子結點數量算法

//求二叉樹的葉子結點 采用遞歸的方式計算葉子結點個數 void GetLeaf(BiTree tree,int* leafNum) {if (NULL != tree){if (tree->lchild == NULL && tree->rchild == NULL){*leafNum += 1;}GetLeaf(tree->lchild,leafNum);GetLeaf(tree->rchild,leafNum);} }

完整代碼

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef char EleType; typedef struct BiTNode {EleType data;//數據結點數據域struct BiTNode *lchild, *rchild;//左孩子,右孩子結點指針域 }BiTNode,*BiTree;//約定通過前序遍歷創建結點 //每個結點都有左右孩子,孩子不存在為NULL void CreatBiTree(BiTree* tree) {char c;scanf("%c",&c);if (' '== c){*tree = NULL;}else{*tree = (BiTNode*)malloc(sizeof(BiTNode));(*tree)->data = c;CreatBiTree(&(*tree)->lchild);//創建左子樹CreatBiTree(&(*tree)->rchild);//創建右子樹} } void VisitNode(EleType data) {printf("%c ", data);return; } //前序遍歷 void PreOrderTraverse(BiTree tree) {if (NULL != tree){VisitNode(tree->data);PreOrderTraverse(tree->lchild);PreOrderTraverse(tree->rchild);} }//求二叉樹的葉子結點 采用遞歸的方式計算葉子結點個數 void GetLeaf(BiTree tree,int* leafNum) {if (NULL != tree){if (tree->lchild == NULL && tree->rchild == NULL){*leafNum += 1;}GetLeaf(tree->lchild,leafNum);GetLeaf(tree->rchild,leafNum);} } //求二叉樹的高度 采用遞歸的方式 void GetHeight(BiTree tree, int* heightNum) {if (NULL != tree){int LHeight;int RHight;GetHeight(tree->lchild,&LHeight);GetHeight(tree->rchild,&RHight);*heightNum = LHeight > RHight ? LHeight + 1 : RHight + 1;}else{*heightNum = 0;} } int main(int argc, char *argv[]) {BiTree tree = NULL;printf("請按前序遍歷的方式輸入結點數據,孩子結點為NULL用空格代替:");CreatBiTree(&tree);printf("前序遍歷:");PreOrderTraverse(tree);int heightNum,leafNum = 0;GetLeaf(tree, &leafNum);GetHeight(tree, &heightNum);printf("\n二叉樹的高度:%d", heightNum);printf("\n二叉樹的葉子結點數目:%d",leafNum);printf("\n");return 0; }

運行結果測試

我們下圖的二叉樹進行測試。


運行結果如下,注意:我們創建結點時的前序輸入:ABC__D__EF__G__,一個_表示一個空格喲。



總結

以上是生活随笔為你收集整理的树:求二叉树的高度和叶子结点数量的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。