uva 548(二叉树)

题解:给出了二叉树的中序和后序,重建二叉树,输出路径和最短的叶子的值。

两个模板:

给出前序和中序建树:

Node* build (int n, int* preo, int* ino) {
    Node* node = new Node;
    int i = 0;
    if (n <= 0)
        return NULL;
    while (ino[i] != preo[0])
        i++;
    node -> val = ino[i];
    node -> left = build(i, preo + 1, ino);
    node -> right = build(n - i - 1, preo + i + 1, ino + i + 1);
    return node;
}

给出中序和后序建树:

Node* build (int n, int* ino, int* post) {
    Node* node = new Node;
    int i = n - 1;
    if (n <= 0)
        return NULL;
    while (ino[i] != post[n - 1])
        i--;
    node -> val = ino[i];
    node -> left = build(i, ino, post);
    node -> right = build(n - i - 1, ino + i + 1, post + i);
    return node;
}

在重建完二叉树后,dfs遍历找到最小路径和叶子。

#include <stdio.h>
const int N = 10010;
const int INF = 0x3f3f3f3f;

struct Node {
    int val;
    Node* left;
    Node* right;
    Node () {
        val = 0;
        left = right = 0;
    }
};
int min, ans;

void init() {
    min = INF;
}

Node* build (int n, int* ino, int* post) {
    Node* node = new Node;
    int i = n - 1;
    if (n <= 0)
        return NULL;
    while (ino[i] != post[n - 1])
        i--;
    node -> val = ino[i];
    node -> left = build(i, ino, post);
    node -> right = build(n - i - 1, ino + i + 1, post + i);
    return node;
}

void dfs (Node* node, int sum) {
    if (node == NULL)
        return;
    sum += node -> val;
    if (node -> left == NULL && node -> right == NULL) {
        if (sum < min) {
            ans = node -> val;
            min = sum;
        }
    }
    else {
        if (node -> left != NULL)
            dfs(node -> left, sum);
        if (node -> right != NULL)
            dfs(node -> right, sum);
    }
}

void Delete(Node* node) {
    if (node == NULL)
        return;
    if (node -> left != NULL)
        Delete(node -> left);
    if (node -> right != NULL)
        Delete(node -> right);
    delete node;
}

int main() {
    int a, n = 0, post[N], ino[N];
    Node* root;
    char c;
    while (scanf("%d%c", &ino[n++], &c) != EOF) {
        if (c == '\n') {
            n = 0;
            while (scanf("%d%c", &post[n++], &c)) {
                if (c == '\n') {
                    init();
                    root = build(n, ino, post);
                    dfs(root, 0);
                    printf("%d\n", ans);
                    Delete(root);
                    n = 0;
                    break;
                }
           }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值