-
Notifications
You must be signed in to change notification settings - Fork 1
/
Largest BST.java
56 lines (47 loc) · 1.27 KB
/
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
//User function Template for Java
// class Node
// {
// int data;
// Node left, right;
// public Node(int d)
// {
// data = d;
// left = right = null;
// }
// }
class Solution{
// Return the size of the largest sub-tree which is also a BST
static public int maxsize=-1;
static int largestBst(Node root)
{
maxsize=-1;
inorder(root);
return maxsize;
}
public static void inorder(Node root){
if(root==null)
return ;
inorder(root.left);
if(isbst(root,Integer.MIN_VALUE,Integer.MAX_VALUE))
{
maxsize=Math.max(maxsize,size(root));
//System.out.println(size(root));
}
inorder(root.right);
//return maxsize;
}
public static int size(Node root){
if(root==null)
return 0;
return size(root.left)+size(root.right)+1;
}
public static boolean isbst(Node root,int min,int max)
{
if(root==null)
return true;
if(min>=root.data||max<=root.data)
return false;
return isbst(root.left,min,root.data)
&&isbst(root.right,root.data,max);
}
}