首页 > 代码库 > uva 548(二叉树)

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;
}