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.

Hint:

  1. You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.

Follow up:

Can you figure out ways to solve it with O(n) time complexity?

Solution:

At first I was thinking using in order traversal, marked out the possible start and end so we just need to find the longest increasing sequence between the a possible start and a possible end. But the thing is how to know which node is a possible start and which node is a possible end.

But it is too hard to figure out the right start and right end.


For example the in order traversal is 42135, but 135 is not the right start and end, so we also need to record the level and it is too complex, however I believe this problem can be solved with in order traversal.


Another thinking way is Divide and conquer, for the left and right subtree, get the max number of the subtree and whether it is the root of that subtree. If one of them are not the root, the whole subtree will not be a BST so just return the max of left and right subtree, otherwise check the min, max and root.val to see whether this subtree is a BST.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    class Result{
        int min;
        int max;
        int num;
        boolean isRoot;
        Result(int min, int max, int num, boolean isRoot){
            this.min = min;
            this.max = max;
            this.num = num;
            this.isRoot = isRoot;
        }
    }
    
    public int largestBSTSubtree(TreeNode root) {
        return helper(root).num;
    }
    
    Result helper(TreeNode root){
        if(root == null) return new Result(Integer.MAX_VALUE,Integer.MIN_VALUE,0,true);
        Result l = helper(root.left);
        Result r = helper(root.right);
        if(l.isRoot && r.isRoot){
            if(root.val > l.max && root.val < r.min){
                return new Result(Math.min(root.val,l.min), Math.max(root.val,r.max), 1 + r.num + l.num, true);  
            } 
        } 
        return new Result(0,0,Math.max(l.num,r.num),false);
    }
}


  





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值