---
# System prepended metadata

title: 0333. Largest BST Subtree
tags: [Leetcode, DFS, Medium]

---

# 0333. Largest BST Subtree
###### tags: `Leetcode` `Medium` `DFS`
Link: https://leetcode.com/problems/largest-bst-subtree/
## 思路
简单dfs 
在每个node那里记录它的subtree的最大值，最小值，以及最大的binary search tree
## Code
```java=
class Solution {
    public int largestBSTSubtree(TreeNode root) {
        int[] res = dfs(root);
        return res[2];
    }
    public int[] dfs(TreeNode root){
        if(root == null){
            return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
        }
        int[] leftRes = dfs(root.left);
        int[] rightRes = dfs(root.right);
        if(leftRes[1]<root.val && root.val<rightRes[0]){
            return new int[]{Math.min(leftRes[0], root.val), Math.max(rightRes[1], root.val), leftRes[2]+rightRes[2]+1};
        }
        else{
            return new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, Math.max(leftRes[2], rightRes[2])};
        }
    }
}
```