您的位置:首页 > 产品设计 > UI/UE

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tree build null delete struct