二叉树的性质我就不多说了,毕竟是笔记,直接上一点干货(代码操作)

  • 根据二叉树的性质,建立一个二叉树存储结构。
typedef char DataType;
/*二叉树存储结构类型*/
typedef struct tonde{
DataType data;
struct tonde *lchile,*rchile;//左孩子,右孩子指针
}BT;
  • 创建一个二叉树,按二叉树带空指针的先序依次输入(解释:因为在创建时我要从根结点开始建立,并且返回这个树根结点,“树高万丈不忘根,人若辉煌不忘本嘛”);

输入:AB0D00CE00F00,“0代表空节点”

注:自己在小本本上演示一下这个代码的递归过程,有利于理解递归这个神奇的的算法。

/*二叉树建立算法描述*/
BT* CreatBTree(){
BT* root;
char ch;
scanf("%c",&ch);
getchar();//吃掉回车键,防止代码出错,是一个字符输入时比较容易出错的地方
if(ch == '0'){
root = NULL;
}else{
root = (BT*)malloc(sizeof(BT));
root->data = ch;
printf("请输入%c的左孩子结点:",root->data);
root->lchile = CreatBTree();//递归建立新的结点
printf("请输入%c的右孩子结点:",root->data);
root->rchile = CreatBTree();
}
return root;
}
  • 二叉树的遍历以及记录总结点数和统计叶子结点数
int count=0;//叶子结点数 
int count_1=0;//二叉树总结点数
void All_Order_Num(BT* root){
if(root == NULL){
return;
}else{
count_1++;//只要结点不为空我就计算一次
printf("%c",root->data);
/*统计二叉树叶子结点的个数,在左右子树都为空的话统计*/
if(root->lchile == NULL && root->rchile == NULL){
count++;
}
All_Order_Num(root->lchile);
All_Order_Num(root->rchile);
}
}

这就是将三个功能放在一起了,但是要注意到把这三个功能分开写和放到一起的递归的形式是一样的,所以才能这样写一下,我老师第一次这样出题,我没反应过来,(ps:没好好看书噻)

  • 求二叉树的深度
    递归统计左子树的深度和右子树深度,递归结束时返回其中最大的一个,即是二叉树的深度。
int TreeDepth(BT *root){

int ldep,rdep;/*求二叉树深度*/
if(root == NULL){
return 0;
}else{
ldep = TreeDepth(root->lchile);
rdep = TreeDepth(root->rchile);
}
if(ldep>rdep){
return ldep+1;
}else{
return rdep+1;
}
}

分开写的几个遍历和统计算法描述:

/*三种输出*/
void PreOrder(BT* root){
if(root == NULL){
return;
}else{
printf("%c",root->data);
PreOrder(root->lchile);
PreOrder(root->rchile);
}
}
void InOeder(BT* root){
if(root == NULL){
return;
}else{
InOeder(root->lchile);
printf("%c",root->data);
InOeder(root->lchile);
}
}
void PostOrder(BT* root){
if(root == NULL){
return;
}else{
InOeder(root->lchile);
InOeder(root->lchile);
printf("%c",root->data);
}
}

统计二叉树叶子结点和二叉树总结点

int count=0;
void Leafnum(BT* root){
if(root){/*统计二叉树叶子结点的个数,在左右子树都为空的话*/
if(root->lchile == NULL && root->rchile == NULL){
count++;
}
Leafnum(root->lchile);
Leafnum(root->rchile);
}
}

void leafsum(BT* root){
if(root){/*求二叉树结点总数*/
count++;
leafsum(root->lchile);
leafsum(root->rchile);
}
}