1ms Java Solution


  • 0
    A
    public class Solution {
        public int largestBSTSubtree(TreeNode root) {
            if(root == null){
                return 0;
            }
            int[] count = new int[1];
            if(isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE, count)){
                return count[0];
            }
            int left = largestBSTSubtree(root.left);
            int right = largestBSTSubtree(root.right);
            return left > right ? left : right;
        }
        
        private boolean isValidBST(TreeNode root, long low, long high, int[] count){
            if(root == null){
                return true;
            }
            if(root.val <= low || root.val >= high){
                return false;
            }
            boolean left = isValidBST(root.left, low, root.val, count);
            boolean right = isValidBST(root.right, root.val, high, count);
            if(left && right){
                count[0]++;
            }
            return left && right;
        }    
    }

  • 0

    @ayumi_Long

    Why does count need to be declared as an integer array?

    It seems you only need to modify count[0].

    Thanks.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.