数据结构:二叉树的构建,遍历,深度,叶子结点

本文详细介绍了二叉树的前序、中序、后序及层次遍历算法,并展示了如何通过先序和中序、后序和中序字符串创建二叉树。此外,还提供了计算树的深度和叶子节点数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct node
{
    char data;
    struct node *lt, *rt;
} ST;
int flag, k;
char str[60];
void fput(ST *root)
{
    if(!root)
        return;
    else
    {
        printf("%c", root->data);
        fput(root->lt);
        fput(root->rt);
    }
}
void midput(ST *root)
{
    if(!root)
        return;
    else
    {
        midput(root->lt);
        printf("%c", root->data);
        midput(root->rt);
    }
}
void behput(ST *root)
{
    if(!root)
        return;
    else
    {
        behput(root->lt);
        behput(root->rt);
        printf("%c", root->data);
    }
}
void cengxu(ST *root)
{
    ST *team[10000];
    int head = 0, last = 0;
    team[last++] = root;
    while(head < last)
    {
        if(team[head])
        {
            printf("%c", team[head]->data);
            team[last++] = team[head]->lt;
            team[last++] = team[head]->rt;
        }
        head++;
    }
}
void leaf(ST *root)
{
    if(root)
    {
        if(!root->lt && !root->rt)
            k++;
        leaf(root->lt);
        leaf(root->rt);
    }
}
ST *fahcreat(int len, char *str1, char *str2)
{
    ST *root;
    int i;
    if(len == 0)
        return NULL;
    root = (ST *)malloc(sizeof(ST));
    root->data = str1[0];
    for(i=0; i<len; i++)
        if(str2[i] == root->data)
            break;
    root->lt = fahcreat(i, str1+1, str2);
    root->rt = fahcreat(len-i-1, str1+i+1, str2+i+1);
    return root;
}
ST *zhcreat(int len, char *str1, char *str2)
{
    if(len <= 0)
        return NULL;
    ST *root;
    root = (ST *)malloc(sizeof(ST));
    root->data = str2[len - 1];
    int p = strchr(str1, str2[len-1]) - str1;
    root->lt = zhcreat(p, str1, str2);
    root->rt = zhcreat(len-p-1, str1+p+1, str2+p);
    return root;
}
int deep(ST *root)
{
    int l = 0, r = 0;
    int max;
    if(root)
    {
        l = deep(root->lt);
        r = deep(root->rt);
        if(l > r)
            max = l;
        else
            max = r;
        return max + 1;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值