4-1 二叉树的基本操作(亲测有效,附带运行截图)(C语言)

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;
}

运行显示;

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值