Consider all Binary Search Trees of height $\le H$ that can be created using the first $N$ natural numbers. Find the sum of the roots of those Binary Search Trees.
For example, for $N$ = 3, $H$ = 3: There are 2 trees with $1$ as root, 1 tree with $2$ as root and 2 trees with $3$ as root.
Hence, $Sum$ = $2*(1) + 1*(2) + 2*(3) = 10$
I am trying to solve this problem by writing a function $f(n,h)$ which is related to $f(n-1,h-1)$ and $f(n-1,h)$ in some way, but unable to find the solution.
Note: All numbers $[1, N]$ must be present in the tree and the height should be $\le H$.
Let's solve a simpler problem first: How many binary search trees are there with $n$ nodes? Call this number $b_n$. We know $b_0 = b_1 = 1$. If you pick $k$ as the root ($1 \le k \le n$), you have $k - 1$ keys to distribute to the left and $n - k - 1$ to the right, so that:
$$ b_n = \sum_{1 \le k \le n} (b_{k - 1} + b_{n - k - 1}) $$
Shift the indices down, and note the symmetry of the sum to get:
$$ b_{n + 1} = 2 \sum_{0 \le k \le n} b_k $$
Define the generating function $B(z) = \sum_{n \ge 0} b_n z^n$, multiply the recurrence by $z^n$ and sum over $n \ge 0$ to get:
$$ \sum_{n \ge 0} b_{n + 1} z^n = 2 \sum_{n \ge 0} z^n \sum_{0 \le k \le n} b_k $$
Recognize some sums here:
$$ \frac{B(z) - b_0}{z} = 2 \frac{B(z)}{1 - z} $$
Pugging in $b_0 = 1$ solution is:
$$ B(z) = \frac{1}{3} + \frac{2}{3} \cdot \frac{1}{1 - 3 z} $$
so that (here $[\text{condition}]$ is Iverson's bracket, $1$ if the condition is true and $0$ if false):
$$ b_n = \frac{2 \cdot 3^n + [n = 0]}{3} $$
Now we are in position to solve your problem if there is no restriction on height. If the root of a binary search tree with $n$ nodes is $k$, there are $k - 1$ nodes in its left subtree and $n - k$ to the right, so the number of binary trees with root $k$ are $b_{k - 1} \cdot b_{n - k}$, and you are asking for:
$\begin{align} \sum_{1 \le k \le n} k b_{k - 1} b_{n - k} &= \sum_{1 \le k \le n} k \frac{2 \cdot 3^{k - 1} + [k = 1]}{3} \cdot \frac{2 \cdot 3^{n - k} + [k = n]}{3} \\ &= 1 \cdot \frac{2 \cdot 3^0 + 1}{3} \cdot \frac{2 \cdot 3^{n - 1}}{3} + n \cdot \frac{2 \cdot 3^{n - 1}}{3} \cdot \frac{2 \cdot 3^0 + 1}{3} + 4 \cdot 3^{n - 3} \sum_{2 \le k \le n - 1} k \\ &= (1 + n) \cdot 2 \cdot 3^{n - 2} + 4 \cdot 3^{n - 3} \left( \frac{n (n - 1)}{2} - 1 \right) \\ &= (2 n^2 + 4 n + 2) \cdot 3^{n - 3} \\ &= 2 (n + 1)^2 \cdot 3^{n - 3} \end{align}$