【算法】解决树型DP问题技巧
树型DP即在“树”的数据结构上的动态规划
技巧
- 根据题目构建合适的返回类
- 获取左右子树的信息
- 加工自己的信息
下面有两个例子可以参考:
判断是否为平衡二叉树
public class IsBalancedTree {
//树型DP
public static boolean isBalanced(Node head) {
return process(head).isBalanced;
}
public static class ReturnType {
public boolean isBalanced;
public int height;
public ReturnType(boolean isB, int h) {
isBalanced = isB;
height = h;
}
}
public static ReturnType process(Node x) {
if (x == null) {
return new ReturnType(true, 0);
}
ReturnType leftR = process(x.left);
ReturnType rightR = process(x.right);
int height = Math.max(leftR.height, rightR.height) + 1;
boolean isBalanced = leftR.isBalanced && rightR.isBalanced
&& Math.abs(leftR.height - rightR.height) < 2;
return new ReturnType(isBalanced, height);
}
}
判断是否为二叉搜索树
public class IsBST {
//树型DP(树型动态规划)
public static boolean isBST(Node<Integer> head) {
return process(head).isBST;
}
public static class ReturnData {
public boolean isBST;
public int min;
public int max;
public ReturnData(boolean isBST, int min, int max) {
this.isBST = isBST;
this.min = min;
this.max = max;
}
}
public static ReturnData process(Node<Integer> x) {
if (x == null) {
return null;
}
ReturnData leftData = process(x.left);
ReturnData rightData = process(x.right);
int min = x.value;
int max = x.value;
if (leftData != null) {
min = Math.min(min, leftData.min);
max = Math.max(max, leftData.max);
}
if (rightData != null) {
min = Math.min(min, rightData.min);
max = Math.max(max, rightData.max);
}
boolean isBST = true;
if (leftData != null && (!leftData.isBST || leftData.max >= x.value)) {
isBST = false;
}
if (rightData != null && (!rightData.isBST || rightData.min <= x.value)) {
isBST = false;
}
return new ReturnData(isBST, min, max);
}
}
本文来自博客园,作者:hzyuan,转载请注明原文链接:https://www.cnblogs.com/hzyuan/p/15834457.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)