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