1.利用先序创建二叉树
2.计算该树有几个结点
3.打印叶子结点
4.计算树中的叶子结点数
5.计算二叉树的高度
6.先序遍历二叉树的输出
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
//1.前序创建二叉树,中序后序遍历方法同理
BiTree Create() {
BiTree root;
ElemType ch;
scanf_s("%c", &ch);
if (ch== '#') return NULL;
else {
root = (BiTree)malloc(sizeof(BiTNode));
root->data = ch;
root->lchild = Create();
root->rchild = Create();
}
return root;
}
//2.统计二叉树的结点数
int PreOrder_GalNode(BiTree root) {
int count = 0;
if(root) {
count= PreOrder_GalNode(root->lchild)+PreOrder_GalNode(root->rchild)+1;
}
return count;
}
//3.打印叶子结点
void print_leafnode(BiTree root) {
if (root) {
print_leafnode(root->lchild);
if (root->lchild == NULL && root->rchild == NULL) {
printf("%c ", root->data);
}
print_leafnode(root->rchild);
}
}
//4.统计叶子结点数
int n = 0;
int LeafNode(BiTree root)//传入根节点
{
if (root != NULL){ //判断非空
if (root->lchild == NULL && root->rchild == NULL){ //如果叶子节点的话,左右节点都为空,则进行n++
n++;
}
LeafNode(root->lchild);
LeafNode(root->rchild);
}
return n;//返回每一次函数调用n的值
}
//5.求二叉树的高度
int TreeDepth(BiTree root) {
int hl, hr, h;
if (root == NULL) return 0;
else {
hl = TreeDepth(root->lchild);
hr = TreeDepth(root->rchild);
h = (hl > hr ? hl : hr) + 1;
return h;
}
}
//6.先序遍历二叉树
void PreOrder(BiTree root) {
if (root) {
printf("%c ", root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
//7.层序遍历二叉树
void Levelorder(BiTree T) {
if (T == NULL) return;
BiTree q[100];
BiTree p = NULL;
int front = 0;
int rear = 0;
q[rear++] = T;
while (front < rear) {
p = q[front++];
printf(" %c", p->data);
if (p->lchild != NULL) {
q[rear++] = p->lchild;
}
if (p->rchild != NULL) {
q[rear++] = p->rchild;
}
}
}
int main(){
//测试输入:AB#DF##G##C##
BiTree T = Create();//1.利用先序创建二叉树
int jiedianshu = PreOrder_GalNode(T);//2.计算该树有几个结点
printf("该树有%d个结点\n",jiedianshu);
printf("叶子结点分别有:");//3.打印叶子结点
print_leafnode(T);
printf("\n");
int leaf_jiedianshu = LeafNode(T);//4.计算树中的叶子结点数
printf("叶子结点有%d个\n", leaf_jiedianshu);
int tree_height = TreeDepth(T);//5.计算二叉树的高度
printf("二叉树的高度为:%d\n", tree_height);
printf("先序遍历二叉树为:");//6.先序遍历二叉树的输出
PreOrder(T);
printf("\n");
printf("层序遍历二叉树为:");//7.层序遍历二叉树的输出
Levelorder(T);
printf("\n");
return 0;
}
运行显示;
