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

Posted 程序媛詹妮弗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 }

 




以上是关于[leetcode]333. Largest BST Subtree最大二叉搜索树子树的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Largest BST Subtree

[Lintcode]184. Largest Number/[Leetcode]179. Largest Number

#Leetcode# 179. Largest Number

LeetCode Largest Divisible Subset

Leetcode410. Split Array Largest Sum

leetcode 179 Largest Number