当前位置:网站首页>基础提升---树形DP补充

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

2022-06-10 17:44:00 星光技术人

题目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);
}
原网站

版权声明
本文为[星光技术人]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qhu1600417010/article/details/124955652