码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]333. Largest BST Subtree最大二叉搜索树子树

时间:2018-06-13 11:57:29      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:amp   ges   not   boolean   max   val   dfs   value   pre   

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 }

 

[leetcode]333. Largest BST Subtree最大二叉搜索树子树

标签:amp   ges   not   boolean   max   val   dfs   value   pre   

原文地址:https://www.cnblogs.com/liuliu5151/p/9175887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!