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.

Example:

Input: [10,5,15,1,8,null,7]

   10 
   / \ 
  5  15 
 / \   \ 
1   8   7

Output: 3
Explanation: 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?

思路:buttom-up,自底向上传递信息,一个是min,一个max,另外一个是是否是bst,result的信息用一个array来保存,这样在遍历整个树的过程中,已经更新了valid bst的个数。这样就是O(n)的复杂度。记住初始值用Long型表达,防止溢出。首先明白了需要自底向上传递信息,那么肯定要建立一个新的数据结构来表达这种信息,然后要明白的是,traverse这个tree还是用原来的TreeNode,但是返回的信息,是自己定义的,就跟int boolean一个道理,所以,这个建立的node跟原来的TreeNode是两个不相关的概念。每走一层,就是建立一个这样的信息节点,然后往上返回。同时,更新res array的信息。这样最后我可以搜刮到关于这个树的信息。也就是最大的BST node数目。

注意:空的节点,需要设置isBST为true;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private class Node {
        public long min;
        public long max;
        public boolean isBST;
        public int size;
        public Node() {
            this.min = Long.MAX_VALUE;
            this.max = Long.MIN_VALUE;
            this.isBST = false;
            this.size = 0;
        }
    }
    
    public int largestBSTSubtree(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int[] res = {0};
        dfs(root, res);
        return res[0];
    }
    
    private Node dfs(TreeNode root, int[] res) {
        Node node = new Node();
        if(root == null) {
            node.isBST = true; // 这个很关键,空的也是valid,这样计算leaf的时候才能正确计算;
            return node;
        }
        
        Node left = dfs(root.left, res);
        Node right = dfs(root.right, res);
        if(left.isBST && left.max < root.val && right.isBST && right.min > root.val) {
            node.isBST = true;
            node.min = Math.min(left.min, root.val);
            node.max = Math.max(right.max, root.val);
            node.size = left.size + right.size + 1;
            res[0] = Math.max(res[0], node.size);
        }
        return node;
    }
}

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值