1.请编程实现二又树的操作。
1.1二又树的创建
1.2二又树的先序遍历
1.3二又树的中序遍历
1.4二又树的后序遍历
1.5二又树各个节点度的个数
1.6二叉树的深度
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char datatype;
//定义节点结构体
typedef struct Node
{//数据域datatype data;//指针域:存储左子孩子节点地址struct Node *lchild;//指针域:存储右子孩子节点地址struct Node *rchild;
}*Btree;//创建节点
Btree create_node()
{Btree s=(Btree)malloc(sizeof(struct Node));if(s==NULL)return NULL;//初始化s->data='\0';s->lchild=s->rchild=NULL;return s;
}
/** function: 创建二叉树* @param [ in] * @param [out] * @return 返回二叉树*/
Btree create_tree()
{datatype element;printf("please enter element:");scanf(" %c",&element);if(element=='#')return NULL;//创建节点Btree tree=create_node();tree->data=element;//递归实现循环左孩子puts("左");tree->lchild=create_tree();//递归实现循环右孩子puts("右");tree->rchild=create_tree();return tree;
}
/** function: 先序遍历* @param [ in] * @param [out] tree* @return */
void first(Btree tree)
{if(NULL==tree)return ;//遍历根节点printf("%c",tree->data);//递归遍历左孩子first(tree->lchild);//递归遍历右孩子first(tree->rchild);
}
//中序遍历
void mid(Btree tree)
{if(NULL==tree)return ;//递归遍历左孩子mid(tree->lchild);//遍历根节点printf("%c",tree->data);//递归遍历右孩子mid(tree->rchild);
}
//后序遍历
void rear(Btree tree)
{if(NULL==tree)return ;//递归遍历左孩子rear(tree->lchild);//递归遍历右孩子rear(tree->rchild);//遍历根节点printf("%c",tree->data);
}
/** function: 计算 度* @param [ in] * @param [out] * @return */void count(Btree tree,int *n0,int *n1,int *n2)
{if(NULL==tree)return ;if(!tree->lchild&&!tree->rchild)++*n0;else if(tree->lchild&&tree->rchild)++*n2;else++*n1;//递归遍历左孩子count(tree->lchild,n0,n1,n2);//递归遍历右孩子count(tree->rchild,n0,n1,n2);
}
/** function: 计算深度* @param [ in] * @param [out] * @return 深度*/
int high(Btree tree)
{if(NULL==tree)return 0;//递归计算左子树的深度int left=1+high(tree->lchild);//递归计算右子树的深度int right=1+high(tree->rchild);return left>right?left:right;
}
int main(int argc, const char *argv[])
{Btree tree=create_tree();//先序遍历
// first(tree);
// puts("");//中序遍历
// mid(tree);
// puts("");//后序遍历rear(tree);puts("");int n0=0,n1=0,n2=0;//计算各个度的个数count(tree,&n0,&n1,&n2);printf("no=%d n1=%d n2=%d n=%d\n",n0,n1,n2,n0+n1+n2);//树的深度int len=high(tree);printf("len=%d\n",len);return 0;
}
先序:
中序:
后序: