Leetcode 95. Unique Binary Search Trees II - Need help understanding the time complexity

149 Views Asked by At

I have a question about understanding the time complexity of the code below. It is the code to generate all unique BST for numbers from 1 to n. I have attached an image of how they describe the time complexity using catalan numbers.

enter image description hereIt is from leetcode:

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

In the solutions it says the time complexity the catalan numbers * n. Why are we trying to express time complexity of an algorithm to generate all the unique BSTs by looking at the total number of BSTs (I read that catalan numbers is the total number of unique BSTs)? Rather than looking at the total number of unique BSTs, shouldn't we look at how much work the algorithm is doing? Shouldn't the time complexity be O(n * 2^n) since we have n numbers to choose from each time to be a root and then we recurse two times, once to create the left child and once to create the right child?

I might be wrong here but I would appreciate any help in breaking down the time complexity of this algorithm.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:        
        arr = list(range(0, n))
        def bt( l, r):
            if l > r:
                
                return [None]
            if l == r:
                return [TreeNode(arr[l]+1)]
            
            else:
                output = []
                for i in range(l , r+1):
                    le = bt(l, i-1)
                    ri = bt(i + 1, r)
                    for x in le:
                        for y in ri:
                            node = TreeNode(arr[i] + 1)
                            node.left = x
                            node.right = y
                            output.append(node)
                return output
        return bt(0, n-1)
0

There are 0 best solutions below