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


     
  • 相关阅读:
    Installutil.exe的位置和路径
    .net服务安装(转载)
    移动程序云测试中心
    如何通过web地址直接调用webservices
    VC++引用类型与指针类型
    Android模拟 HTTP multipart/formdata 请求协议信息实现图片上传
    firefox看网页的插件
    DOS下输入汉字
    电脑APK
    HDOJ 1071(球泡无线和直线区域内的面积)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14939783.html
Copyright © 2011-2022 走看看