剧透警告
如果你想自己解决这个问题,请不要阅读代码。
一种解决方法是将数据转换成树形结构(实际上是图),然后编写递归算法,通过将树缩小为更小的子树(直到只剩一个节点的树),并从那里开始向上移动,找到通过树的最大路径。
我非常喜欢递归算法和处理树形结构,所以我继续编写了一个程序来完成它:
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
struct node {
node(int i, node* left = NULL, node* right = NULL) : data(i), left(left), right(right) { }
node* left, *right;
int data;
};
std::vector<node*> maxpath(node* tree, int& sum) {
if (!tree) {
sum = -1;
return std::vector<node*>();
}
std::vector<node*> path;
path.push_back(tree);
if (!tree->left && !tree->right) {
sum = tree->data;
return path;
}
int leftsum = 0, rightsum = 0;
auto leftpath = maxpath(tree->left, leftsum);
auto rightpath = maxpath(tree->right, rightsum);
if (leftsum != -1 && leftsum > rightsum) {
sum = leftsum + tree->data;
copy(begin(leftpath), end(leftpath), back_inserter<vector<node*>>(path));
return path;
}
sum = rightsum + tree->data;
copy(begin(rightpath), end(rightpath), back_inserter<vector<node*>>(path));
return path;
}
int main()
{
node b5[] = { node(4), node(5), node(2), node(6), node(5) };
node b4[] = { node(2, &b5[0], &b5[1]), node(7, &b5[1], &b5[2]), node(4, &b5[2], &b5[3]), node(4, &b5[3], &b5[4]) };
node b3[] = { node(8, &b4[0], &b4[1]), node(1, &b4[1], &b4[2]), node(0, &b4[2], &b4[3]) };
node b2[] = { node(3, &b3[0], &b3[1]), node(8, &b3[1], &b3[2]) };
node n(7, &b2[0], &b2[1]);
int sum = 0;
auto mpath = maxpath(&n, sum);
for (int i = 0; i < mpath.size(); ++i) {
cout << mpath[i]->data;
if (i != mpath.size() - 1)
cout << " -> ";
}
cout << endl << "path added up to " << sum << endl;
}
它打印出来了
7 -> 3 -> 8 -> 7 -> 5
路径加起来为30
7, 3, 8, 7, 5
的总和比通过树的任何其他路径的数字的总和都要大。 - Seth Carnegie