算法题之Node Selection

题目:

    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;
}

想法:

动态规划,分层问题。想清楚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值