UVA 548 - Tree

本文深入探讨了数据结构和算法的应用实例,包括二叉树、队列、栈、数组、链表、B树、散列表等核心概念,以及排序算法、动态规划、哈希算法、贪心算法、深度优先搜索、近邻算法、霍夫曼树、电梯算法、遗传算法和广度优先搜索等关键算法。通过实例讲解,展示了如何在实际问题中高效地运用这些基础知识。
#include<cstdio>
#include<cstring>
#include<cstdlib>
int mid[10010],post[10010],max,leaf;
typedef struct node Tnode;
struct node
{
    int data;
    Tnode *left;
    Tnode *right;
};
Tnode *newnode()
{
    Tnode *p = (Tnode *)malloc(sizeof(Tnode));
    p->data = 0;
    p->left = NULL;
    p->right = NULL;
    return p;
}
Tnode *creat(int *mid,int *post,int len,int sum)
{
     //puts("---");
    if(len<=0)
        return NULL;
    sum += post[len-1];
    if(len==1)
    {
        if(sum < max)
        {
            max = sum;
            leaf = post[len-1];
        }
        else if(sum == max)
        {
            if(leaf > post[len-1])
                leaf = post[len-1];
            return NULL;
        }
    }
    int p = len-1;
    while(post[len-1]!=mid[p])
        p--;
    Tnode *q = newnode();//puts("---");
    q->data = post[len-1];//printf("%d %d...\n",post[len-1],p);
    q->left = creat(mid,post,p,sum);
    q->right = creat(mid+p+1,post+p,len-p-1,sum);
    return q;
}
int remove(Tnode *root)
{
    if(!root) return 0;
    root->data = 0;
    remove(root->left);
    remove(root->right);
}
int search(int len,int i,int *mid,int *post)
{
     max = 1<<30;
    Tnode *root = creat(mid,post,len,0);
    printf("%d\n",leaf);
    remove(root);
}
int main()
{
    char c;
    int len;
    for(len=0; scanf("%d%c",&mid[len++],&c)==2;)
    {
        if(c=='\n')
        {
            for(int i = 0; i < len; i++)
                scanf("%d",&post[i]);
            search(len,0,mid,post);
            len = 0;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值