import
java.util.*;
class
Node {
int
data;
Node left;
Node right;
Node(
int
num)
{
data = num;
left =
null
;
right =
null
;
}
}
class
Main {
static
int
target, ans;
static
Map<Node, Integer> minv =
new
HashMap<>();
static
Map<Node, Integer> maxv =
new
HashMap<>();
static
Map<Node, Integer> h =
new
HashMap<>();
static
Map<Node, Integer> sum =
new
HashMap<>();
public
static
boolean
isBST(Node root)
{
if
(root ==
null
)
return
true
;
if
(root.left ==
null
&& root.right ==
null
) {
minv.put(root, root.data);
maxv.put(root, root.data);
h.put(root,
1
);
sum.put(root, root.data);
if
(sum.get(root) == target)
ans = Math.min(ans, h.get(root));
return
true
;
}
if
(root.left ==
null
) {
if
(isBST(root.right)
&& minv.get(root.right) > root.data) {
minv.put(root, root.data);
maxv.put(root, maxv.get(root.right));
h.put(root, h.get(root.right) +
1
);
sum.put(root,
sum.get(root.right) + root.data);
if
(sum.get(root) == target)
ans = Math.min(ans, h.get(root));
return
true
;
}
return
false
;
}
if
(root.right ==
null
) {
if
(isBST(root.left)
&& maxv.get(root.left) < root.data) {
minv.put(root, minv.get(root.left));
maxv.put(root, root.data);
h.put(root, h.get(root.left) +
1
);
sum.put(root,
sum.get(root.left) + root.data);
if
(sum.get(root) == target)
ans = Math.min(ans, h.get(root));
return
true
;
}
return
false
;
}
boolean
bstleft = isBST(root.left);
boolean
bstright = isBST(root.right);
if
(bstleft && bstright
&& maxv.get(root.left) < root.data
&& minv.get(root.right) > root.data) {
minv.put(root, minv.get(root.left));
maxv.put(root, maxv.get(root.right));
h.put(root,
1
+ h.get(root.left) + h.get(root.right));
sum.put(root, root.data + sum.get(root.left) + sum.get(root.right));
if
(sum.get(root) == target)
ans = Math.min(ans, h.get(root));
return
true
;
}
return
false
;
}
public
static
int
minSubtreeSumBST(
int
k, Node root)
{
ans = Integer.MAX_VALUE;
target = k;
isBST(root);
if
(ans == Integer.MAX_VALUE)
return
-
1
;
return
ans;
}
public
static
void
main(String[] args)
{
int
k =
38
;
Node root =
new
Node(
13
);
root.left =
new
Node(
5
);
root.right =
new
Node(
23
);
root.left.right =
new
Node(
17
);
root.left.right.left =
new
Node(
16
);
int
res = minSubtreeSumBST(k, root);
System.out.println(res);
}
}