樹:求二叉樹的高度和葉子結點數量
阿新 • • 發佈:2019-01-03
演算法程式碼很簡單都是用使用遞迴計算,大家把遞迴思想領悟到就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__,一個_表示一個空格喲。