LeetCode[333] Largest BST Subtree

LeetCode[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.

Recursion

复杂度
O(N), O(lgN)

思路
考虑对于每一个节点来说,能组成的largest binary tree的size。

if(isBinary(node.left) && isBinary(node.right)) {
    if(node.val > node.left.val && node.val < node.right.val) {
        //
        那么node is binary
        并且node.cnt = node.left.cnt + node.right.cnt;
    }
}
else {
    return node is not binary && Math.max(node.left.cnt, node.right.cnt);
}

所以我们需要两个返回值,一个是这个node是不是binary tree,另一个是当前的node能组成的最大size的值。

可以考虑定义一个新node来返回这两个结果,或者通过返回一个数组,数组里面包含着两个值来返回这两个结果。

代码

int num = 0;
public int largestBSTSubtree(TreeNode root) {
    helper(root);
    return num;
}

// in[] = {isBST, size, max, min};
public int[] helper(TreeNode root) {
    if(root == null) return new int[]{1, 0, Integer.MIN_VALUE, Integer.MAX_VALUE};
    int[] left = helper(root.left);
    int[] right = helper(root.right);
    int res = new int[4];
    res[2] = Math.max(root.val, right[2]);
    res[3] = Math.min(root.val, left[3]);
    // 这个node能构成一个Binary tree
    if(left[0] == 1 && right[0] == 1 && root.val > left[2] && root.val < right[3]) {
        res[0] = 1;
        res[1] = left[1] + right[1] + 1;
        num = Math.max(num, res[1]);
        return res;
    }
    // 这个node不能构成一个binary tree
    res[0] = 0;
    res[1] = Math.max(left[1], right[1]);
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值