• LeetCode 333. 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.

    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 }
  • 相关阅读:
    洛谷P1071 潜伏者
    2019BJFU 网站设计(孙俏-web前端开发)实验代码-181002222
    反思——P1307 数字反转
    洛谷P1067 多项式输出
    湖南大学第十五届程序设计竞赛(重现赛)
    2019河北省大学生程序设计竞赛(重现赛)
    2019BJFU C++实验习题(完结)
    配置android source 在ubuntu中编译环境
    Android屏幕保持唤醒状态
    Android richtext
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5187436.html
Copyright © 2020-2023  润新知