码迷,mamicode.com
首页 > 其他好文 > 详细

uva 548(二叉树)

时间:2014-07-25 11:26:21      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:uva   数据结构   二叉树   

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

两个模板:

给出前序和中序建树:

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


uva 548(二叉树),布布扣,bubuko.com

uva 548(二叉树)

标签:uva   数据结构   二叉树   

原文地址:http://blog.csdn.net/hyczms/article/details/38096315

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!