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


     
  • 相关阅读:
    从零开始~
    SVN
    了解下几个证书~~
    重要的技术发展趋势
    求职路上英语面试试题问答大全
    C语言比java重要吗?
    开源solr搜索服务器配置
    全文索引 与 Like 的实现原理
    nginx搭建多个站点
    .Solr构建索引查询索引
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14939783.html
Copyright © 2011-2022 走看看