uva 548(二叉樹)
阿新 • • 發佈:2017-07-10
int nod class turn pri trac -a uva min
在重建完二叉樹後,dfs遍歷找到最小路徑和葉子。
題解:給出了二叉樹的中序和後序。重建二叉樹。輸出路徑和最短的葉子的值。
兩個模板:
給出前序和中序建樹:
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(二叉樹)