【算法】解决树型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);
    }
}
posted @   hzyuan  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示