using
System;
using
System.Collections.Generic;
class
GFG {
public
class
Node {
public
int
data;
public
Node left;
public
Node right;
}
static
Node newNode(
int
d)
{
Node n =
new
Node();
n.data = d;
n.left =
null
;
n.right =
null
;
return
n;
}
static
void
findwt(Node root,
int
[] wt,
SortedDictionary<
int
,
int
> um,
int
width)
{
if
(root ==
null
) {
return
;
}
if
(um.ContainsKey(width)) {
um[width] = um[width] + wt[root.data];
}
else
{
um.Add(width, wt[root.data]);
}
findwt(root.left, wt, um, width - 1);
findwt(root.right, wt, um, width + 1);
}
static
void
solveQueries(
int
[] wt, Node root,
int
[][] queries)
{
SortedDictionary<
int
,
int
> um
=
new
SortedDictionary<
int
,
int
>();
findwt(root, wt, um, 0);
int
x = 0;
SortedDictionary<
int
,
int
> newUm
=
new
SortedDictionary<
int
,
int
>();
foreach
(KeyValuePair<
int
,
int
> it
in
um)
{
x += it.Value;
newUm.Add(it.Key, x);
}
um = newUm;
for
(
int
i = 0; i < queries.Length; i++) {
int
l = queries[i][0];
int
r = queries[i][1];
int
ans = 0;
if
(um.ContainsKey(r)) {
ans = um[r];
}
if
(um.ContainsKey(l - 1)) {
ans -= um[l - 1];
}
Console.WriteLine(ans);
}
}
public
static
void
Main(
string
[] args)
{
int
N = 8;
Node root = newNode(1);
root.left = newNode(3);
root.left.left = newNode(5);
root.left.right = newNode(6);
root.right = newNode(2);
root.right.right = newNode(4);
root.right.right.left = newNode(7);
root.right.right.right = newNode(0);
int
[] wt = { 8, 6, 4, 5, 1, 2, 9, 1 };
int
[][] queries
= {
new
int
[] { -1, 1 },
new
int
[] { -2, -1 },
new
int
[] { 0, 3 } };
solveQueries(wt, root, queries);
}
}