数据结构(五)树
- 一、基本操作
树是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;
}