forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestBSTSubtree.java
39 lines (30 loc) · 1.04 KB
/
LargestBSTSubtree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package medium;
import classes.TreeNode;
public class LargestBSTSubtree {
public int largestBSTSubtree(TreeNode root) {
if(root == null) return 0;
if(isBST(root)) return getNodes(root);
return Math.max(find(root.left), find(root.right));
}
int find(TreeNode root){
if(isBST(root)) return getNodes(root);
return Math.max(find(root.left), find(root.right));
}
int getNodes(TreeNode root){
if(root == null) return 0;
return dfsCount(root);
}
int dfsCount(TreeNode root){
if(root == null) return 0;
return dfsCount(root.left) + dfsCount(root.right) + 1;
}
boolean isBST(TreeNode root){
if(root == null) return true;
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
boolean dfs(TreeNode root, long min, long max){
if(root == null) return true;
if(root.val <= min || root.val >= max) return false;
return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}
}