树:求二叉树的高度和叶子结点数量
生活随笔
收集整理的這篇文章主要介紹了
树:求二叉树的高度和叶子结点数量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
算法代碼很簡單都是用使用遞歸計算,大家把遞歸思想領悟到就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__,一個_表示一個空格喲。
總結
以上是生活随笔為你收集整理的树:求二叉树的高度和叶子结点数量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VC++动态库封装及调用
- 下一篇: Kali网址