数据结构----二叉树叶子结点到根节点的高度计算
生活随笔
收集整理的這篇文章主要介紹了
数据结构----二叉树叶子结点到根节点的高度计算
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
數(shù)據(jù)結(jié)構(gòu)----二叉樹葉子結(jié)點(diǎn)到根節(jié)點(diǎn)的高度計(jì)算
代碼:
#include<stdio.h> #include<stdlib.h> typedef struct bstTree {int data;struct bstTree* lchild, *rchild; }bstTree; void createBSTTree(bstTree* & T, int data) {//創(chuàng)建二叉排序樹bstTree *p = NULL;if (!T) {p = (bstTree*)malloc(sizeof(bstTree));p->data = data;p->lchild = p->rchild = NULL;T = p;return;}if (data < T->data) {//左子樹插入createBSTTree(T->lchild, data);}else {//右子樹插入createBSTTree(T->rchild, data);} } void prePrint(bstTree* BSTTree) {//前序遍歷二叉排序樹if (BSTTree) {printf("%d ", BSTTree->data);prePrint(BSTTree->lchild);prePrint(BSTTree->rchild);} } void calLeafHeight(bstTree* T,int h) {//計(jì)算葉子結(jié)點(diǎn)到根節(jié)點(diǎn)的高度if (!T) {return;}if (T->lchild == NULL && T->rchild == NULL) {printf("%d葉子結(jié)點(diǎn)到根節(jié)點(diǎn)的高度為%d\n", T->data, h + 1);}else {calLeafHeight(T->lchild, h + 1);//左孩子calLeafHeight(T->rchild, h + 1);//右孩子} } int main() {bstTree* T = NULL;//一定要初始化為空樹int count, data;printf("開始構(gòu)造二叉排序樹:\n輸入二叉排序樹結(jié)點(diǎn)的數(shù)目:");scanf_s("%d", &count);while (count--) {//構(gòu)造二叉排序樹printf("輸入二叉排序樹的第%d個(gè)結(jié)點(diǎn):", count + 1);scanf_s("%d", &data);createBSTTree(T, data);}printf("前序遍歷二叉排序樹\n");prePrint(T);//前序遍歷二叉排序樹printf("\n");calLeafHeight(T, 0);printf("\n");system("pause");return 0; }測(cè)試截圖:
時(shí)間復(fù)雜度O(logn),空間復(fù)雜度O(1)
如果存在什么問題,歡迎批評(píng)指正!謝謝!
總結(jié)
以上是生活随笔為你收集整理的数据结构----二叉树叶子结点到根节点的高度计算的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用VScode的EIDE插件进行51单
- 下一篇: word List 19