题目:
You are given a binary tree, and each node in the tree has a positive integer weight. If you select a node, then its children and parent nodes cannot be selected. Your task is to find a set of nodes, which has the maximum sum of weight.
代码:
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
using namespace std;
struct Tree {
Tree* left;
Tree* right;
int value;
Tree(int v) {
value = v;
left = NULL;
right = NULL;
}
};
map<Tree*, int> opt;
int nodeSelect(Tree* root) {
if (opt[root] != 0) {
return opt[root];
}
if (!root)return 0;
int w1 = 0, w2 = root->value;
if (root->left) {
w1 += nodeSelect(root->left);
w2 += nodeSelect(root->left->left) + nodeSelect(root->left->right);
}
if (root->right) {
w1 += nodeSelect(root->right);
w2 += nodeSelect(root->right->left) + nodeSelect(root->right->right);
}
opt[root] = w1 > w2 ? w1 : w2;
return opt[root];
}
int main() {
Tree* t1 = new Tree(1);
Tree* t2 = new Tree(2);
Tree* t3 = new Tree(10);
Tree* t4 = new Tree(11);
Tree* t5 = new Tree(3);
Tree* t6 = new Tree(4);
Tree* t7 = new Tree(12);
t1->left = t2;
t1->right = t3;
t2->left = t4;
t3->left = t5;
t3->right = t6;
t2->right = t7;
int weight = nodeSelect(t1);
return 0;
}
想法:
动态规划,分层问题。想清楚。