• 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);
    }
    
    


     
  • 相关阅读:
    1.border-image
    CSS3 3D transform
    js表单的focus()与blur()方法
    jquery背景backgroundPosition插件
    数字反转
    js的字符串charAt()方法
    FormData使用方法详解
    封装自己的jquery插件
    webpack打包vue项目之后怎么启动&注意事项
    JavaScript中的async/await
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14939783.html
Copyright © 2020-2023  润新知