二叉树与递归

给中序遍历和后续遍历,求从根到叶子权值最小的路径,的叶子节点的值。若有多条,求叶子最小的。

#include <iostream>

#include <string>

#include <sstream>

#include <cstring>

using namespace std;

const int maxn = 10005;

struct node{

    int data;

    node *lc,*rc;

    node(int d) : data(d),lc(NULL),rc(NULL) {}

};

int in[maxn],post[maxn];

node* build(int *in,int *post,int n)

{

    if(n == 0) return NULL;

    int rt = post[n - 1];

    node *root = new node(rt);

    int p = 0;

    while (p < n && in[p] != rt) {

        p ++;

    }

    int l = p,r = n - p - 1;

    if(l > 0)

        root->lc = build(&in[0], &post[0], l);

    if(r > 0)

        root->rc = build(&in[p + 1], &post[p], r);

    return root;

}

int minsum = 1 << 20,u = maxn;

//递归的时候,函数调用的栈其实就记录了在每个节点,从根至此的sum。

void dfs(node *cur,int sum)//sum为当前最小值

{

    sum += cur->data;

    if (cur->lc == NULL && cur->rc == NULL) {//为叶子节点

        if (sum < minsum ||(sum == minsum && cur->data < u)) {

            u = cur->data;

            minsum = sum;

        }

    }

    if (cur->lc != NULL) {

        dfs(cur->lc, sum);

    }

    if(cur->rc != NULL)

    {

        dfs(cur->rc,sum);

    }

}


int main()

{

    string a;

    while (getline(cin,a)) {

        memset(in, 0, sizeof(in));

        memset(post, 0, sizeof(post));

        int sz  = 0;

        stringstream ss(a);

        while (ss) {

            ss >> in[sz ++];

        }

        ss.clear();ss.str("");//清空状态并赋为空串

        getline(cin ,a);

       sz = 0;

        ss << a;

        while (ss) {

            ss >> post[sz ++];

        }

        node *root = build(in,post,sz - 1);

        minsum = 1 << 20,u = maxn;

        dfs(root, 0);

        printf("%d\n",u);

    }

    return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值