数据结构(五)树
數據結構(五)樹
- 一、基本操作
樹是n個節點的有限集,它是一種遞歸的數據結構
一、基本操作
#include <stdio.h> #include <stdlib.h> #include <iostream>#define Elemtype charusing namespace std; typedef struct BiTNode {Elemtype data;struct BiTNode* lchild, * rchild; }BitTNode, * BiTree;//初始化二叉樹 bool InitBiTree(BiTree &T) {T = (BitTNode*)malloc(sizeof(BitTNode));if (T == NULL){printf("tree error!\n");exit(1);}T->lchild = NULL;T->rchild = NULL;return true; } //創建樹 bool createBiTree(BiTree& T) {char ch;cin>>ch;if (ch == '.'){T = NULL; //如果輸入 '.' , 該樹空結點}else{T = (BitTNode*)malloc(sizeof(BitTNode));if (T == NULL){printf("tree error!\n");exit(1);}T->data = ch;createBiTree(T->lchild);createBiTree(T->rchild);}return true; }//先序遍歷 bool ProOrderTree(BiTree& T) {if (T) //非空{printf("%c\t", T->data);ProOrderTree(T->lchild);ProOrderTree(T->rchild);}return true; } //中序遍歷 bool inOrderTree(BiTree& T) {if (T) //非空{ProOrderTree(T->lchild);printf("%c\t", T->data);ProOrderTree(T->rchild);}return true;} //后序遍歷 bool postOrderTree(BiTree& T) {if (T) //非空{ProOrderTree(T->lchild);ProOrderTree(T->rchild);printf("%c\t", T->data);}return true;} //刪除樹 bool DestroyBiTree(BiTree& T) {if (T){ProOrderTree(T->lchild);ProOrderTree(T->rchild);free(T);T = NULL;}return true;}//判空 bool BiTreeEmpty(BiTree T) {if (T){return false;}else{return true;} }//求樹的深度 int BiTreeDepth(BiTree T) {int ldepth;//用來存放左子樹的深度int rdepth;if (!T)//樹空{return 0;}ldepth = BiTreeDepth(T->lchild);rdepth = BiTreeDepth(T->rchild);return (ldepth > rdepth) ? (ldepth + 1) : (rdepth + 1); } //節點數 int NodeCount(BiTree T) {if (T == NULL){return 0;}return NodeCount(T->lchild) + NodeCount(T->rchild) + 1; }//求二叉樹第k層的結點個數 int GetLevelNums(BiTree T, int k) {if (k == 0 || T == NULL){return 0;}if (k == 1){return 1;}return GetLevelNums(T->lchild, k - 1) + GetLevelNums(T->rchild, k - 1);}int main() {BiTree T;//InitBiTree(T);createBiTree(T);ProOrderTree(T);return 0; }總結
- 上一篇: 我家英雄联盟团战的时候为什么很卡?是哪里
- 下一篇: 王国保卫战4南瓜灯杰克怎么获得