您的位置:首页 > 其它

UVa 548 Tree

2010-03-09 09:02 351 查看
/*
coder: ACboy
date: 2010-3-9
result: 1A
description: UVa 548 Tree
*/

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;

struct tree {
// 左右子树
struct tree * lchild;
struct tree * rchild;
// 节点的值
int value;
// 用于标记是否是叶子节点
int ifleaf;
};

// 使用递归的方法构造二叉树,参数向量a是用来存储中序遍历的数据
// 参数向量b是用来存储后序遍历的数据
tree * buildTree(vector<int> & a, vector<int> & b)
{
tree * p = new tree();
int alen = a.size();
int blen = b.size();
// 如果只有一个数据则说明是叶子节点
if (alen == 1) {
p->value = a[0];
p->ifleaf = 1;
p->lchild = p->rchild = NULL;
return p;
}
// 因为b向量中存储在后序遍历的结果所以最后一个数据就是当前树的根节点
int rootValue= b[blen - 1];
// 对根节点的进行赋值
p->value = rootValue;
p->ifleaf = 0;
// 查找根节点在中序遍历中的位置
int rootPos = find(a.begin(), a.end(), rootValue) - a.begin();
// 把向量a和b分别分割为他们的左右子树的中序遍历和后序遍历向量
// 左子树的中序遍历
vector<int> aleftTree;
// 右子树的中序遍历
vector<int> arightTree;
// 左子树的后序遍历
vector<int> bleftTree;
// 右子树的后序遍历
vector<int> brightTree;
int i;
for (i = 0; i < alen; i++)
{
if (i < rootPos)
aleftTree.push_back(a[i]);
else if (i > rootPos)
arightTree.push_back(a[i]);
}
for (i = 0; i < blen - 1; i++) {
if (i < rootPos) {
bleftTree.push_back(b[i]);
} else {
brightTree.push_back(b[i]);
}
}

// 递归创建树。
if (aleftTree.size() == 0) {
p->lchild = NULL;
} else {
p->lchild = buildTree(aleftTree, bleftTree);
}
if (arightTree.size() == 0) {
p->rchild = NULL;
} else {
p->rchild = buildTree(arightTree, brightTree);
}
return p;
}

// 深度优先遍历树
void dfs(tree * p) {
tree * stack[10500];
int top = 0;
stack[top++] = p;
int total = p->value;
int totalLeastValue = 200000000;
int leastValue = INT_MAX;
tree * cur = p;
while (top != 0) {
cur = stack[top - 1];
if (cur != NULL) {
if (cur->lchild != NULL) {
stack[top++] = cur->lchild;
cur->lchild = NULL;
total += stack[top - 1]->value;
} else if (cur->rchild != NULL) {
stack[top++] = cur->rchild;
cur->rchild = NULL;
total += stack[top - 1]->value;
} else if (cur->ifleaf == 1) {
//total += stack[top - 1]->value;
if (total < totalLeastValue) {
totalLeastValue = total;
leastValue = stack[top - 1]->value;
}
if (total == totalLeastValue && stack[top - 1]->value < leastValue) {
leastValue = stack[top - 1]->value;
}
total -= stack[top - 1]->value;
top--;
} else {
total -= stack[top - 1]->value;
top--;
}
}
}
cout << leastValue << endl;
}

int main()
{

vector<string> ve;
string input;
#ifndef ONLINE_JUDGE
freopen("548.txt", "r", stdin);
#endif
while (getline(cin, input)) {
ve.push_back(input);
}
int len = ve.size();
int i;
for (i = 0; i < len; i += 2)
{
int temp;
vector<int> a, b;
istringstream in;
in.str(ve[i]);
while (!in.eof())
{
in >> temp;
a.push_back(temp);
}
istringstream in1;
in1.str(ve[i + 1]);

while (!in1.eof()) {
in1 >> temp;
b.push_back(temp);
}

tree * root = buildTree(a, b);
dfs(root);
a.clear();
b.clear();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息