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?
做了好久 大概知道问题在哪了 对于每一个节点 都需要一个最小 最大值
其实之前在判断一棵树是否是bst的时候用过这种想法 
    
class Result {  // (size, rangeLower, rangeUpper) -- size of current tree, range of current tree [rangeLower, rangeUpper]
        int size;
        int lower;
        int upper;
        
        Result(int size, int lower, int upper) {
            this.size = size;
            this.lower = lower;
            this.upper = upper;
        }
    }
    
    int max = 0;
    
    public int largestBSTSubtree(TreeNode root) {
        if (root == null) { return 0; }    
        traverse(root);
        return max;
    }
    
    private Result traverse(TreeNode root) {
        if (root == null) { return new Result(0, Integer.MAX_VALUE, Integer.MIN_VALUE); }
        Result left = traverse(root.left);
        Result right = traverse(root.right);
        if (left.size == -1 || right.size == -1 || root.val <= left.upper || root.val >= right.lower) {
            return new Result(-1, 0, 0);//1.
        }
        int size = left.size + 1 + right.size;
        max = Math.max(size, max);
        return new Result(size, Math.min(left.lower, root.val), Math.max(right.upper, root.val));
    }

1.这里为什么返回-1

当这棵树的任何一边不满足二叉树条件的时候 这棵树就不是二叉树

比如 输入是 

     4

   / \

20    3

4的左节点不符合条件 left.size=-1 右边符合 right.size=1

left.size+1+right.size=1

返回的最大子树应该是1 也就是3或者20这两个节点 而不是2

-1相当于是用来抵消根节点


猜你喜欢

转载自blog.csdn.net/daimingyang123/article/details/79383380
BST
333