moonlightshadow123
6/23/2017 - 8:14 AM

96. Unique Binary Search Trees

  1. Unique Binary Search Trees
class Solution(object):
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 0:
            return 0
        recd = [0]*(n+1)
        # There are recd[i] ways to organize a tree with i nodes.
        recd[0] = 1
        recd[1] = 1
        for i in range(2,n+1):
            for j in range(1,i+1):
                # j as the root node of the BST
                # The left tree has `j-1` nodes and the right tree has `i-j` nodes.
                recd[i] += recd[j-1] * recd[i-j]
        return recd[n]

https://leetcode.com/problems/unique-binary-search-trees/#/description

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example, Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3