import
java.util.*;
class
GFG{
static
boolean
ans;
static
class
node
{
int
data;
node left;
node right;
};
static
class
minMax
{
boolean
isBST;
boolean
balanced;
int
size;
int
height;
int
min;
int
max;
public
minMax(
boolean
isBST,
boolean
balanced,
int
size,
int
height,
int
min,
int
max)
{
super
();
this
.isBST = isBST;
this
.balanced = balanced;
this
.size = size;
this
.height = height;
this
.min = min;
this
.max = max;
}
public
minMax()
{
}
};
static
node createNode(
int
value)
{
node temp =
new
node();
temp.left =
null
;
temp.right =
null
;
temp.data = value;
return
temp;
}
static
minMax findBalancedBstUtil(node root,
int
k)
{
if
(root ==
null
)
return
new
minMax(
true
,
true
,
0
,
0
,
Integer.MAX_VALUE,
Integer.MIN_VALUE );
minMax temp =
new
minMax();
minMax lsTree = findBalancedBstUtil(root.left,
k);
if
(ans ==
true
)
return
temp;
minMax rsTree = findBalancedBstUtil(root.right,
k);
if
(ans ==
true
)
return
temp;
if
(!lsTree.isBST || !rsTree.isBST ||
lsTree.max > root.data ||
rsTree.min < root.data)
{
temp.isBST =
false
;
return
temp;
}
if
(Math.abs(lsTree.height -
rsTree.height) ==
1
||
Math.abs(lsTree.height -
rsTree.height) ==
0
)
temp.balanced =
true
;
else
temp.balanced =
false
;
temp.isBST =
true
;
temp.size =
1
+ lsTree.size +
rsTree.size;
temp.height = Math.max(lsTree.height,
rsTree.height) +
1
;
temp.min = root.left !=
null
?
lsTree.min : root.data;
temp.max = root.right !=
null
?
rsTree.max : root.data;
if
(temp.balanced ==
true
&&
temp.size == k)
{
ans =
true
;
}
return
temp;
}
static
String findBalancedBst(node root,
int
k)
{
ans =
false
;
findBalancedBstUtil(root, k);
return
ans ==
true
?
"Yes"
:
"No"
;
}
public
static
void
main(String[] args)
{
node root = createNode(
15
);
root.left = createNode(
10
);
root.right = createNode(
26
);
root.left.left = createNode(
5
);
root.left.right = createNode(
12
);
root.right.left = createNode(
25
);
root.right.left.left = createNode(
20
);
root.right.right = createNode(
40
);
root.right.right.left = createNode(
35
);
root.right.right.right = createNode(
50
);
root.right.right.right.right = createNode(
60
);
int
k =
4
;
System.out.print(findBalancedBst(root, k));
}
}