基础提升---树形DP补充

题目1:最大距离

在这里插入图片描述
在这里插入图片描述
节点距离表示某两个节点之间的节点的个数;求以某节点为根节点的树中所有节点距离的最大距离

  • 思路分析
    节点A的最大距离有三种情况:
  1. 节点A参与
    节点A左子树的最大深度+右子树的最大深度+1
    2)节点A不参与
    max(左子树最大距离,右子树最大距离)

所以树形DP写法需要返回两个信息:i.最大深度 ii.最大距离

  • code
#include<iostream>
using namespace std;

struct TreeNode
{
	TreeNode* left;
	TreeNode* right;
};

class returntype
{
public:
	int  maxheight;
	int max_dis;
	returntype(int mh, int md)
	{
		maxheight = mh;
		max_dis = md;
	}
};


returntype get_dis(TreeNode* root)
{
	if (root == nullptr)
	{
		return returntype(0, 0);
	}
	returntype L_info = get_dis(root->left);
	returntype R_info = get_dis(root->right);

	//列举可能性
	//根节点参与
	int p1 = L_info.maxheight;
	int p2 = R_info.maxheight;
	int p = p1 + p2 + 1;
	int max_h = max(p1, p2) + 1;
	//根节点不参与
	int p3 = L_info.max_dis;
	int p4 = R_info.max_dis;

	int max_d = max(p, max(p3, p4));

	return returntype(max_h, max_d);
}

题目2:宴会问题,打家劫舍

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 分析
    同样仿照上题的思路,加入根节点为A,左右孩子分别为B和C;那么整个树的最大快乐值L_A由以下几个部分组成:
    1) A参与情况下
    节点A的值+节点B整棵树,不包含B的最大快乐值+节点B整棵树,不包含B的最大快乐值
    2)A不参与的情况
    0+max(B来,最大快乐值;B不来的最大快乐之值) + max(C来的最大快乐值;C不来的最大快乐值)

  • code(写法一)

#include<iostream>
using namespace std;

struct TreeNode
{
	int v;
	TreeNode* left;
	TreeNode* right;
};

class returntype
{
public:
	int in_maxH;
	int out_maxH;
	returntype(int i, int o)
	{
		in_maxH = i;
		out_maxH = o;
	}
};

returntype get_maxhappy(TreeNode* root)
{
	if (root == nullptr)
	{
		return returntype(0, 0);
	}
	returntype L_info = get_maxhappy(root->left);
	returntype R_info = get_maxhappy(root->right);

	//A参与
	int p1 = root->v + L_info.out_maxH + R_info.out_maxH;
	//A不参与
	int p2 = max(L_info.in_maxH, L_info.out_maxH) + max(R_info.in_maxH, R_info.out_maxH);
	
	int p = max(p1, p2);

	return returntype(p1, p2);
}
  • code2(写法二)
#include<iostream>
#include<vector>
using namespace std;

struct TreeNode
{
	int v;
	vector<TreeNode*> nexts;
};

class returntype
{
public:
	int in_maxH;
	int out_maxH;
	returntype(int i, int o)
	{
		in_maxH = i;
		out_maxH = o;
	}
};

//写法二
returntype Get_maxhappy(TreeNode* root)
{
	if (root->nexts.size()==0)
		return returntype(root->v, 0);

	int in_happy = root->v;
	int out_happy = 0;
	for (auto n : root->nexts)
	{
		in_happy += Get_maxhappy(n).in_maxH;
		out_happy += max(Get_maxhappy(n).out_maxH, Get_maxhappy(n).in_maxH);
	}

	return returntype(in_happy, out_happy);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星光技术人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值