import
java.util.*;
class
GFG {
static
class
Node {
Node left;
Node right;
int
data;
Node(
int
data)
{
this
.data = data;
this
.left =
null
;
this
.right =
null
;
}
};
static
class
Info {
int
num_BST;
int
max;
int
min;
boolean
isBST;
Info(
int
a,
int
b,
int
c,
boolean
d)
{
num_BST = a;
max = b;
min = c;
isBST = d;
}
Info()
{
}
};
static
Info NumberOfBST(Node root)
{
if
(root ==
null
)
return
new
Info(
0
, Integer.MIN_VALUE,
Integer.MAX_VALUE,
true
);
if
(root.left ==
null
&& root.right ==
null
)
return
new
Info(
1
, root.data, root.data,
true
);
Info L = NumberOfBST(root.left);
Info R = NumberOfBST(root.right);
Info bst =
new
Info();
bst.min = Math.min(root.data, (Math.min(L.min, R.min)));
bst.max = Math.max(root.data, (Math.max(L.max, R.max)));
if
(L.isBST && R.isBST && root.data > L.max && root.data < R.min) {
bst.isBST =
true
;
bst.num_BST =
1
+ L.num_BST + R.num_BST;
}
else
{
bst.isBST =
false
;
bst.num_BST = L.num_BST + R.num_BST;
}
return
bst;
}
public
static
void
main(String args[])
{
Node root =
new
Node(
5
);
root.left =
new
Node(
9
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
6
);
root.right.right =
new
Node(
4
);
root.left.left.left =
new
Node(
8
);
root.left.left.right =
new
Node(
7
);
System.out.print(NumberOfBST(root).num_BST);
}
}