zoukankan      html  css  js  c++  java
  • 333. Largest BST Subtree节点数最多的bst子树

    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.

    Example:

    Input: [10,5,15,1,8,null,7]
    
       10 
       /  
      5  15 
     /     
    1   8   7
    
    Output: 3
    Explanation: The Largest BST Subtree in this case is the highlighted one.
                 The return value is the subtree's size, which is 3.

    本来以为是生成left,right这样。没想到用math.max比较一下就行了
    还有个很好用的用traverse写的bst validation

    复习时不会的地方:countNode不用left =, right =,直接返回1+left+right就行了


    参考:https://leetcode.com/problems/largest-bst-subtree/discuss/78896/Clean-and-easy-to-understand-Java-Solution
    public int largestBSTSubtree(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        if (isValid(root, null, null)) return countNode(root);
        return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
    }
    
    public boolean isValid(TreeNode root, Integer min, Integer max) {
        if (root == null) return true;
        if (min != null && min >= root.val) return false;
        if (max != null && max <= root.val) return false;
        return isValid(root.left, min, root.val) && isValid(root.right, root.val, max);
    }
    
    public int countNode(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        return 1 + countNode(root.left) + countNode(root.right);
    }
    
    


     
  • 相关阅读:
    robotframework-ride1.7.3.1更新安装
    批量删除新浪微博
    Redis
    GET和POST两种基本请求方法的区别
    selenium2自动化测试实战--基于Python语言
    同步/异步/阻塞/非阻塞/BIO/NIO/AIO
    HTTP抓包实战
    LCT模板(BZOJ2631)
    树链剖分模板(BZOJ3083)
    凸包(BZOJ1069)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14939783.html
Copyright © 2011-2022 走看看