public
class
VerticalSumBST {
static
class
Node {
int
data;
Node left;
Node right;
Node(
int
val)
{
data = val;
left =
null
;
right =
null
;
}
}
static
long
res;
static
Node targetNode;
static
void
down(Node node,
int
direction)
{
if
(node !=
null
) {
if
(direction ==
0
)
res += node.data;
down(node.left, direction -
1
);
down(node.right, direction +
1
);
}
}
static
void
find(Node node,
int
target)
{
if
(targetNode ==
null
) {
if
(node !=
null
) {
if
(node.data > target)
find(node.left, target);
else
if
(node.data < target)
find(node.right, target);
else
{
targetNode = node;
down(node,
0
);
}
}
}
}
static
long
verticallyDownBST(Node root,
int
target)
{
res = -target;
targetNode =
null
;
find(root, target);
if
(res == -target)
return
-
1
;
return
res;
}
public
static
void
main(String[] args)
{
Node root =
new
Node(
25
);
root.left =
new
Node(
20
);
root.right =
new
Node(
35
);
root.left.left =
new
Node(
15
);
root.left.right =
new
Node(
22
);
root.right.left =
new
Node(
30
);
root.right.right =
new
Node(
45
);
root.right.right =
new
Node(
45
);
root.right.left.right =
new
Node(
32
);
int
target =
35
;
long
result = verticallyDownBST(root, target);
if
(result != -
1
)
System.out.println(
"Largest Sum Vertically Down from Target ("
+ target +
"): "
+ result);
else
System.out.println(
"No valid target node found."
);
}
}