10
    / \
   5  15
  / \   \ 
 1   8   7

return 3
public class Solution {
    public int largestBSTSubtree(TreeNode root) {
        if(root == null) return 0;
        int[] res = recursive(root);
        return res[2];
    }
    
    public int[] recursive(TreeNode root){
        int[] res = new int[5];
        // res[0] BST or Not?
        // res[1] total number nodes of subtree
        // res[2] max number of BST subtree 
        // res[3] min
        // res[4] max
        res[0] = 1; res[3] = Integer.MAX_VALUE; res[4] = Integer.MIN_VALUE;
        if(root == null) return res;
        
        int[] resL = recursive(root.left);
        int[] resR = recursive(root.right);
        if(resL[0] == 0 || resR[0] == 0 || resL[4] >= root.val || resR[3] <= root.val) 
            res[0] = 0;
        res[1] = resL[1] + resR[1] + 1;
        res[2] = (res[0] == 1) ? res[1]: Math.max(resL[2], resR[2]);
        res[3] = root.val < resL[3] ? root.val : resL[3];
        res[4] = root.val > resR[4] ? root.val : resR[4];
        return res;
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。