(精)先中、中后建树;先中后、层序输出;深度高度、叶子结点

(以输入字符为例)

通过中序、后序建树

struct tree *creat(char *a, char *b, int n) // 通过中序、后序建树
{
    if(n <= 0) return NULL;
    struct tree *root;
    root = (struct tree *)malloc(sizeof (struct tree));
    root->data = b[n - 1];
    int i;
    for(i = 0; i < n; i++)
    {
        if(a[i] == b[n - 1]) break;
    }
    root->l = creat(a, b, i);
    root->r = creat(a + i + 1, b + i, n - i - 1);
    return root;
};

通过前(先)序、中序建树

struct tree *creat(char a[], char b[], int n) // 通过前(先)序、中序建树
{
    if(n <= 0) return NULL;
    struct tree *root;
    root = (struct tree *)malloc(sizeof(struct tree));
    root->data = a[0];
    int i;
    for(i = 0; i < n; i++)
    {
        if(b[i] == a[0]) break;
    }
    root->l = creat(a + 1, b, i);
    root->r = creat(a + i + 1, b + i + 1, n - i - 1);
    return root;
};

先序给定空结点建树

struct tree *creat(char *a) // 先序给定空结点建树
{
    struct tree *root;
    if(a[++i] == ',') root = NULL; // 定义全局变量i,在main函数中赋值为-1
    else
    {
        root = (struct tree *)malloc(sizeof(struct tree));
        root->data = a[i];  // 注意这里不需要再++
        root->l = creat(a);
        root->r = creat(a);
    }
    return root;
};

层序输出

void at_out(struct tree *root) // 层序输出
{
    if(root == NULL) return;
    int t = 0, i = 0;
    struct tree *s[100], *q; //指针类型数组
    s[0] = root;
    while(t <= i)
    {
        q = s[t++];
        printf("%c", q->data);
        if(q->l != NULL)
        {
            s[++i] = q->l;
        }
        if(q->r != NULL)
        {
            s[++i] = q->r;
        }
    }
}


// 前(先)序输出:根左右

void pre_out(struct tree *root)
{
    if(root)
    {
        printf("%c", root->data);
        pre_out(root->l);
        pre_out(root->r);
    }
}


// 中序输出:左根右

void mid_out(struct tree *root)
{
    if(root)
    {
        pre_out(root->l);
        printf("%c", root->data);
        pre_out(root->r);
    }
}


// 后序输出:左右根

void aft_out(struct tree *root)
{
    if(root)
    {
        pre_out(root->l);
        pre_out(root->r);
        printf("%c", root->data);
    }
}

求最大深度,求高度

int depth(struct tree *root) // 求最大深度,求高度
{
    int ld, rd;
    if(!root) return 0;
    else
    {
        ld = depth(root->l);
        rd = depth(root->r);
        return ld > rd ? ld + 1 : rd + 1;
    }
}

查找叶子结点(统计个数)
 

void leaf(struct tree *root) // 查找叶子结点(统计个数)
{
    if(root)
    {
        leaf(root->l);
        leaf(root->r);
        if(!root->l && !root->r)
        {
            leaf_num++;
        }
    }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WMYBlog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值