【算法】解决树型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

浙公网安备 33010602011771号