Java 7ms solution.


  • 0
    J

    Java 7ms solution.

    public class Solution {
        public int largestBSTSubtree(TreeNode root) {
            if (isBST(root)==true) return count(root);
            else {
                return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));                        
            }
        }
        
        public boolean isBST(TreeNode root) {
            return BST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }    
            
        public boolean BST(TreeNode root, int min, int max) {    
            if (root==null) return true;
            else if (root.val>=max || root.val<=min) return false; 
            else return BST(root.left, min, root.val) && BST(root.right, root.val, max);        
        }
        
        public int count(TreeNode root) {
            if (root==null) return 0;
            else return 1 + count(root.left) + count(root.right); 
        }
    }
    

Log in to reply
 

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