333. Largest BST Subtree

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.
Here's an example:

    10
    / \

5
  15

/ \
   \ 

1   8
   7

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?

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private class JieTree{
        int count;
        boolean isBST;
        int minVal;
        int maxVal;

        public JieTree(int count, boolean isBST, int minVal, int maxVal){
            this.count = count;
            this.isBST = isBST;
            this.minVal = minVal;
            this.maxVal = maxVal;
        }
    }

    int ans = 0;
    public int largestBSTSubtree(TreeNode root) {

        dfs(root);

        return ans;
    }

    private JieTree dfs(TreeNode root){
        if (root == null){
            return new JieTree(0, true, Integer.MAX_VALUE, Integer.MIN_VALUE);
        }
        if (root.left == null && root.right == null){
            ans = Math.max(ans, 1);
            return new JieTree(1, true, root.val, root.val);
        }

        JieTree leftRes = dfs(root.left);
        JieTree rightRes = dfs(root.right);

        boolean isCurrentBST = leftRes.isBST && rightRes.isBST && root.val > leftRes.maxVal && root.val < rightRes.minVal;
        int count = leftRes.count + rightRes.count + 1;
        int currentMin = Math.min(leftRes.minVal, root.val);
        int currentMax = Math.max(rightRes.maxVal, root.val);
        if (isCurrentBST) ans = Math.max(ans, count);

        //System.out.println("current root: " + root.val + " is bst: " + isCurrentBST + " count: " + count);

        return new JieTree(count, isCurrentBST, currentMin, currentMax);

    }
}

results for ""

    No results matching ""