国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] Largest BST Subtree

Youngdze / 941人閱讀

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:

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
public class Solution {
    public int largestBSTSubtree(TreeNode root) {
        if (root == null) return 0;
        if (isValidBST(root)) return largestBSTSubtree(root.left)+largestBSTSubtree(root.right)+1;
        else return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
    }
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean dfs(TreeNode root, long min, long max) {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65189.html

相關文章

  • LeetCode[333] Largest BST Subtree

    摘要:復雜度思路考慮對于每一個節點來說,能組成的的。那么并且所以我們需要兩個返回值,一個是這個是不是,另一個是當前的能組成的最大的值。代碼這個能構成一個這個不能構成一個 LeetCode[333] Largest BST Subtree Given a binary tree, find the largest subtree which is a Binary SearchTree (B...

    WrBug 評論0 收藏0
  • [LeetCode] 333. Largest BST Subtree

    Problem 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 descen...

    tigerZH 評論0 收藏0
  • 333. Largest BST Subtree

    10 / 5 15 / 1 8 7 return 3 public class Solution { public int largestBSTSubtree(TreeNode root) { if(root == null) return 0; int[] res = recursive(root); ...

    DataPipeline 評論0 收藏0
  • [LeetCode] 776. Split BST

    Problem Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, whil...

    baiy 評論0 收藏0
  • [LeetCode] 501. Find Mode in Binary Search Tree

    Problem Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node c...

    NikoManiac 評論0 收藏0

發表評論

0條評論

Youngdze

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<