您的位置:首页 > 其它

Largest BST Subtree

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int largestBSTSubtree(TreeNode root) {
        if(root == null) return 0;
        int[] res = {0};
        collect(root, res);
        return res[0];
    }
     
    public Node collect(TreeNode root, int[] res){
        Node node = new Node();
         
        if(root == null){
            node.isBST = true;
            return node;
        }
         
        Node leftnode = collect(root.left, res);
        Node rightnode = collect(root.right, res);
        if(leftnode.isBST && leftnode.max < root.val && rightnode.isBST && root.val < rightnode.min){
            node.isBST = true;
            node.min = Math.min(root.val, leftnode.min);
            node.max = Math.max(root.val, rightnode.max);
            node.size = leftnode.size + rightnode.size + 1;
            res[0] = Math.max(res[0], node.size);
        }
        return node;
    }
     
    class Node{
        long min;
        long max;
        boolean isBST = false;
        int size;
        public Node(){
            min = Long.MAX_VALUE;
            max = Long.MIN_VALUE;
            size = 0;
        }
    }
     
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: