zoukankan      html  css  js  c++  java
  • Leetcode: 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?

    refer to https://discuss.leetcode.com/topic/36995/share-my-o-n-java-code-with-brief-explanation-and-comments/2

    这道题不好从root到leaf一层一层限制subtree取值范围,因为有可能parent并不能构成BST,反倒是需要如果subtree是BST的话,限制parent的取值范围,然后根据情况判断是:

    1. 吸纳parent以及parent的另一个subtree进来形成一个更大的BST,向上传递这个新subtree的size

    2. parent向上传递自它以下发现的最大BST

    所以我们需要传递subtree size, subtree (min, max)范围,所以我们想到用一个wrapper class包括这三项东西。

    同时因为要能分辨上面1、2两种情况,所以size为正表示1,size为负表示2

     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 class Result {
    12         int res;
    13         int min;
    14         int max;
    15         public Result(int num, int n1, int n2) {
    16             this.res = num;
    17             this.min = n1;
    18             this.max = n2;
    19         }
    20     }
    21     
    22     public int largestBSTSubtree(TreeNode root) {
    23         Result res = findLargestBST(root);
    24         return Math.abs(res.res);
    25     }
    26     
    27     public Result findLargestBST(TreeNode cur) {
    28         if (cur == null) return new Result(0, Integer.MAX_VALUE, Integer.MIN_VALUE);
    29         Result left = findLargestBST(cur.left);
    30         Result right = findLargestBST(cur.right);
    31         if (left.res<0 || right.res<0 || cur.val<left.max || cur.val>right.min) {
    32             return new Result(Math.max(Math.abs(left.res), Math.abs(right.res))*(-1), 0, 0);
    33         }
    34         else return new Result(left.res+right.res+1, Math.min(left.min, cur.val), Math.max(right.max, cur.val));
    35     }
    36 }
  • 相关阅读:
    《未来简史》一、主导世界力量的形成与崩塌
    《小岛经济学》九、美岛应对危机——汽油救火
    《小岛经济学》八、金本位的破灭、房地产的泡沫
    《小岛经济学》七、美国的生命线正是我们中国
    《小岛经济学》六、政府手中的魔术棒
    《小岛经济学》五、政府与央行的上帝之手
    《小岛经济学》四、最成功的栽赃——通货紧缩
    《小岛经济学》三、是什么在拉动经济的增长
    11.boolean类型
    10.整形数据类型
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6181811.html
Copyright © 2011-2022 走看看