DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

Constraints:

  • 1 <= n <= 19

SOLUTION:

class Solution:
    def getTrees(self, beg, end):
        if beg > end:
            return 1
        if (beg, end) in self.cache:
            return self.cache[(beg, end)]
        ways = 0
        for i in range(beg, end + 1):
            ways += self.getTrees(beg, i - 1) * self.getTrees(i + 1, end)
        self.cache[(beg, end)] = ways
        return ways

    def numTrees(self, n: int) -> int:
        self.cache = {}
        return self.getTrees(1, n)
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay