uva 548 - Tree
2012-07-04 00:19
225 查看
// uva 548 - Tree // 题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=489 // 题目大意: 求从根节点到叶节点路径和最小的叶节点,如果有多组,输出叶节点最小的 #include <cstdio> #include <string> #include <iostream> using namespace std; const int MAXN = 10010; struct Node{ int val, sum; Node *left, *right; } *root, *minSum; int arrIn[MAXN], arrPost[MAXN]; Node* Build(int ,int ,int ,int); void Release(Node*); void FindLeaf(); void AddSum(Node*, int); void Init(); int main(){ while(scanf("%d", &arrIn[0]) != EOF){ Init(); int nCnt = 1; while(getchar() != '\n') scanf("%d", &arrIn[nCnt++]); for(int i = 0; i < nCnt; i++) scanf("%d", &arrPost[i]); root = Build(0, nCnt - 1, 0, nCnt - 1); FindLeaf(); cout << minSum->val << endl; Release(root); } return 0; } void Init (){ minSum = NULL; } Node* Build(int il, int ir, int pl ,int pr){ int inVal = arrPost[pr]; int inPos; for(inPos = il; inPos <= ir; inPos++){ if(arrIn[inPos] == inVal) break; } Node* nowNode = new Node(); nowNode->val = inVal; if (il != inPos){ nowNode->left = Build (il, inPos - 1, pl, pl + inPos - il - 1); } if (ir != inPos){ nowNode->right = Build (inPos + 1, ir, pr - 1 - (ir - inPos - 1), pr- 1); } return nowNode; } void Release(Node* root){ if(root->left) Release(root->left); if(root->right) Release(root->right); delete root; return; } void FindLeaf(){ AddSum(root, 0); } void AddSum (Node* root, int sum){ root->sum = sum + root->val; if(root->left == NULL && root-> right == NULL) { if(minSum == NULL || root->sum < minSum->sum || root->sum == minSum->sum && root->val > minSum-> val){ minSum = root; } } if (root->left) AddSum(root->left, root->sum); if (root->right) AddSum (root->right, root->sum); }
相关文章推荐
- 【UVA 548 Tree】二叉树构造 & 遍历
- 548 - Tree (UVa OJ)
- UVa 548 Tree
- UVa 548 Tree【二叉树的递归遍历】
- uva 548 - Tree
- uva 548 tree
- UVA 548 - Tree
- uva 548 Tree
- 例题6-8 UVa548 Tree(树的遍历转换)
- UVA 548 tree
- uva 548 tree(中序后序还原树)
- Uva548——Tree
- UVA 548 Tree
- 例题6-8 树 Tree UVa 548 中序遍历+后序遍历建树
- Tree UVA - 548
- Uva - 548 - Tree
- uva 548 tree
- UVA - 548 Tree
- uva 548 tree 二叉树的各种遍历
- uva 548 -Tree