LeetCode Largest BST Subtree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Largest BST Subtree相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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.

 

Show Hint 

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

    采用bottom-up的方法,简历新的class, 用来存储

    • 当前节点为root的subtree是否是BST
    • 若是,最小val 和最大val.
    • size是当前subtree的大小。

    然后从下到上更新,若是中间过程中size 比 res大,就更新res.

    Time Complexity: O(n). 每个点不会访问超过两遍. Space: O(logn). Recursion stack space.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int largestBSTSubtree(TreeNode root) {
    12         int [] res = {0};
    13         helper(root, res);
    14         return res[0];
    15     }
    16     
    17     private Node helper(TreeNode root, int [] res){
    18         Node cur = new Node();
    19         if(root == null){
    20             cur.isBST = true;
    21             return cur;
    22         }
    23         Node left = helper(root.left, res);
    24         Node right = helper(root.right, res);
    25         if(left.isBST && root.val > left.max && right.isBST && root.val < right.min){
    26             cur.isBST = true;
    27             cur.min = Math.min(root.val, left.min);
    28             cur.max = Math.max(root.val, right.max);
    29             cur.size = left.size + right.size + 1;
    30             if(cur.size > res[0]){
    31                 res[0] = cur.size;
    32             }
    33         }
    34         return cur;
    35     }
    36 }
    37 
    38 class Node{
    39     boolean isBST;
    40     int min;
    41     int max;
    42     int size;
    43     public Node(){
    44         isBST = false;
    45         min = Integer.MAX_VALUE;
    46         max = Integer.MIN_VALUE;
    47         size = 0;
    48     }
    49 }

     

    以上是关于LeetCode Largest BST Subtree的主要内容,如果未能解决你的问题,请参考以下文章

    [LeetCode] Largest BST Subtree 最大的二分搜索子树

    Leetcode 333: Largest BST Subtree

    LeetCode "Largest BST Subtree"

    [leetcode]333. Largest BST Subtree最大二叉搜索树子树

    [Lintcode]184. Largest Number/[Leetcode]179. Largest Number

    #Leetcode# 179. Largest Number