首页 > 代码库 > 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。