Problem
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.Example:Input: [10,5,15,1,8,null,7] 10 / \ 5 15 / \ \ 1 8 7Output: 3Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?Solution
First try:
class Solution { public int largestBSTSubtree(TreeNode root) { if (root == null) return 0; if (isBST(root)) return largestBSTSubtree(root.left)+largestBSTSubtree(root.right)+1; return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } private boolean isBST(TreeNode root) { if (root == null) return true; if (root.left != null && findMax(root.left) >= root.val) return false; if (root.right != null && findMin(root.right) <= root.val) return false; if (isBST(root.left) && isBST(root.right)) return true; return false; } private int findMax(TreeNode root) { while (root.right != null) root = root.right; return root.val; } private int findMin(TreeNode root) { while (root.left != null) root = root.left; return root.val; }}
Optimized:
class Solution { public int largestBSTSubtree(TreeNode root) { if (root == null) return 0; if (isBST(root, null, null)) return largestBSTSubtree(root.left)+largestBSTSubtree(root.right)+1; return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } private boolean isBST(TreeNode root, Integer min, Integer max) { if (root == null) return true; if (min != null && min >= root.val) return false; if (max != null && max <= root.val) return false; if (isBST(root.left, min, root.val) && isBST(root.right, root.val, max)) return true; return false; }}