Leetcode333-最大BST子树

  • 本体关键就是二叉树加递归
  • 在递归中用int数组保存需要的内容
//二叉树加递归 注意int[]返回值很关键
public class L333 {
    private int ans;

    public int largestBSTSubtree(TreeNode root) {
        isBST(root);
        return ans;
    }

    private int[] isBST(TreeNode root) {
        if (root == null) {
            return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0, 1};
        }
        int[] left = isBST(root.left);
        int[] right = isBST(root.right);

        // 最小值
        int min = Math.min(root.val, Math.min(left[0], right[0]));
        // 最大值
        int max = Math.max(root.val, Math.max(left[1], right[1]));
        // 节点个数
        int count = left[2] + right[2] + 1;
        // 是否是bst (0 不是 1 是)
        int flag = (left[3] == right[3] && left[3] == 1 && root.val > left[1] && root.val < right[0]) ? 1 : 0;
        // 更新最大bst
        if (flag == 1) ans = Math.max(ans, count);
        return new int[]{min, max, count, flag};
    }
}
posted @ 2022-05-09 10:01  fao99  阅读(91)  评论(0)    收藏  举报