简繁EN

LeetCodeNo. 106

[LeetCode with Python] 96. Unique Binary Search Trees

Contents

Problem

Problem page: https://leetcode.com/problems/unique-binary-search-trees/
Topics: Tree, Dynamic Programming
Difficulty: Medium
Similar problems: (M) Unique Binary Search Trees II

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
2
3
4
5
1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

Analysis

Given a node count, I need to find how many different binary search trees I can build.
Once I pick the root of a binary search tree, everything in the left subtree has to be smaller than the root and everything on the right larger. So the number of possible shapes depends only on the number of nodes. With a straight recursive search, if I have n nodes to allocate to the current subtree, I try every split (the root takes one node; the left and right subtree sizes start at 0 and n-1, then 1 and n-2, and so on up to n-1 and 0), then recurse on both subtrees.
The problem is that if I don't save the results, I solve the same subproblem over and over. For n nodes, I make two direct recursive calls for each subproblem from 0 to n-1 nodes (once for the left subtree and once for the right), so each extra node triples the total number of calls. So I use dynamic programming.
I use counts[i] for the number of different binary search trees I can build with i nodes. I set counts[0]=1 because the empty tree counts as one. If the total is nodes, I put left nodes in the left subtree and the remaining right=nodes-left-1 in the right subtree. The two subtree shapes are independent, so there are counts[left]×counts[right] possible trees for this split. I sum those counts over all the splits to get counts[nodes].
I work my way from counts[1] to counts[n]. Each entry uses only entries with smaller indices, which I've already worked out. counts[n] is the nth Catalan number because the Catalan numbers are defined by the same recurrence and also start with 1 at index 0. There are two nested loops. The inner loop tries each value of left, for a total of 1+2+...+n=n(n+1)/2 iterations. That puts the time complexity at O(n^2). The counts array of length n+1 is all I need, so the space complexity is O(n).


Code

1
2
3
4
5
6
7
8
9
10
class Solution:
# @return an integer
def numTrees(self, n):
counts = [0 for i in range(0, n + 1)] # counts[i]: unique BSTs with i nodes
counts[0] = 1
for nodes in range(1, n + 1):
for left in range(0, nodes):
right = nodes - left - 1 # 1 as the sub-root node
counts[nodes] += counts[left] * counts[right]
return counts[n]

Article link: https://xnerv.wang/en/leetcode-unique-binary-search-trees/