• [leetcode]333. 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.

    题意:

    给定二叉树,找出最大的二叉搜索树子树。

    思路:

    代码:

     1 class Solution {
     2     public int largestBSTSubtree(TreeNode root) {
     3         if(root == null) return 0;
     4         return dfs(root)._size;
     5     }
     6     
     7     private Result dfs(TreeNode root){
     8         if(root == null) return new Result (true, 0, 999, -999);
     9         
    10         Result leftResult = dfs(root.left);
    11         Result rightResult = dfs(root.right);
    12         
    13         boolean isBST = ((root.right == null ||(rightResult._isBST) && (rightResult._min > root.val)) && (root.left == null || (leftResult._isBST)&&(leftResult._max < root.val )));
    14         int size = isBST ? (leftResult._size + rightResult._size +1) : Math.max(leftResult._size, rightResult._size);
    15         int min  = root.left == null ? root.val : leftResult._min;
    16         int max = root.right == null ? root.val : rightResult._max;
    17         return new Result(isBST, size, min, max);
    18             
    19     }
    20     
    21     private class Result{
    22         boolean _isBST;
    23         int _size;
    24         int _min;
    25         int _max;
    26         private Result(boolean isBST, int size, int min, int max){
    27             _isBST = isBST;
    28             _size = size;
    29             _min = min;
    30             _max = max;
    31         }
    32     }    
    33 }
  • 相关阅读:
    职场之道
    AlphaBlend
    感动前行——给医学媳妇写的演讲稿(非IT类)
    高等数学积分公式大全
    分析Model2系统心得
    【软考】(六)关系代数
    飞鸽传书官方站点 创立黑马程序猿训练营
    实现简单的二级级联
    const和readonly差别
    Chord算法(原理)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9175887.html
Copyright © 2020-2023  润新知