-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_166_Largest_BST.java
71 lines (55 loc) · 1.96 KB
/
a_166_Largest_BST.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class a_166_Largest_BST {
static class Node{
int data ;
Node left;
Node right ;
Node(int data){
this.data = data ;
this.left = this.right = null ;
}
}
static class Info{
boolean isBST ;
int size ;
int min ;
int max ;
public Info(boolean isBST , int size, int min, int max){
this.isBST = isBST ;
this.size = size ;
this.min = min ;
this.max = max ;
}
}
public static int maxBST = 0 ;
public static Info largestBST(Node root){
if(root == null){
return new Info(true, 0, Integer.MAX_VALUE, Integer.MIN_VALUE) ;
}
Info leftInfo = largestBST(root.left) ;
Info rightInfo = largestBST(root.right) ;
int size = leftInfo.size + rightInfo.size + 1 ;
int min = Math.min(root.data, Math.min(leftInfo.min, rightInfo.min)) ;
int max = Math.max(root.data, Math.max(leftInfo.max, rightInfo.max)) ;
if(root.data <= leftInfo.max || root.data >= rightInfo.min){
return new Info(false, size, min, max) ;
}
if(leftInfo.isBST && rightInfo.isBST){
maxBST = Math.max(maxBST, size) ;
return new Info(true, size, min, max) ;
}
return new Info(false, size, min, max) ;
}
public static void main(String[] args) {
Node root = new Node(50) ;
root.left = new Node(30) ;
root.left.left = new Node(5) ;
root.left.right = new Node(20) ;
root.right = new Node(60) ;
root.right.left = new Node(45) ;
root.right.right = new Node(70) ;
root.right.right.left = new Node(65) ;
root.right.right.right = new Node(80) ;
Info ans = largestBST(root) ;
System.out.println("Largest BST size = "+ maxBST);
}
}