Largest BST Subtree
10
/ \
5 15
/ \ \
1 8 7
Input:{10,5,15,1,8,#,7}
Output:3
The Largest BST Subtree in this case is :
5
/ \
1 8.
The return value is the subtree's size, which is 3.public class Solution {
public int largestBSTSubtree(TreeNode root) {
if (root == null) return 0;
if (isValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE)) return count(root);
return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
}
private boolean isValid(TreeNode root, Integer min, Integer max) {
if (root == null) return true;
if (min >= root.val || max <= root.val) return false;
return isValid(root.left, min, root.val) && isValid(root.right, root.val, max);
}
private int count(TreeNode root) {
if (root == null) return 0;
return count(root.left) + count(root.right) + 1;
}
}Last updated