using
System;
using
System.Collections.Generic;
public
class
Node {
public
int
data;
public
Node left, right;
public
Node(
int
x)
{
this
.data = x;
this
.left =
null
;
this
.right =
null
;
}
}
public
class
Solution {
Dictionary<Node,
int
> subTreeLength, sum, mnE, mxE;
int
minLength =
int
.MaxValue;
int
target;
public
int
MinSubtreeSumBST(
int
target, Node root)
{
this
.target = target;
subTreeLength =
new
Dictionary<Node,
int
>();
sum =
new
Dictionary<Node,
int
>();
mnE =
new
Dictionary<Node,
int
>();
mxE =
new
Dictionary<Node,
int
>();
IsBST(root);
return
minLength ==
int
.MaxValue ? -1 : minLength;
}
public
int
IsBST(Node root)
{
if
(root ==
null
)
return
1;
int
l = IsBST(root.left);
int
r = IsBST(root.right);
int
leftSum = 0;
int
rightSum = 0;
if
(root.left !=
null
) {
leftSum = sum[root.left];
}
if
(root.right !=
null
) {
rightSum = sum[root.right];
}
sum[root] = root.data + leftSum + rightSum;
int
leftMin = root.left !=
null
? mnE[root.left]
: root.data;
int
rightMax = root.right !=
null
? mxE[root.right]
: root.data;
mnE[root] = Math.Min(root.data, leftMin);
mxE[root] = Math.Max(root.data, rightMax);
subTreeLength[root]
= 1
+ (root.left !=
null
? subTreeLength[root.left]
: 0)
+ (root.right !=
null
? subTreeLength[root.right]
: 0);
if
((root.left !=
null
? mxE[root.left] < root.data
:
true
)
&& (root.right !=
null
? mnE[root.right] > root.data
:
true
)
&& l != 0 && r != 0) {
if
(target == sum[root])
minLength = Math.Min(minLength,
subTreeLength[root]);
return
1;
}
return
0;
}
}
public
class
GFG {
public
static
void
Main(
string
[] args)
{
int
target = 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);
Solution obj =
new
Solution();
int
result = obj.MinSubtreeSumBST(target, root);
Console.WriteLine(result);
}
}