官方解答写的很好搬运一下
Given an integer n
, return all the structurally unique BST's (binary search trees), which has exactly n
nodes of unique values from 1
ton
. Return the answer in any order.
Example 1:
Input: n = 3 Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Example 2:
Input: n = 1 Output: [[1]]
Approach 1: Recursion
First of all let's count how many trees do we have to construct. As you could check in this article, the number of possible BST is actually a Catalan number.
Let's follow the logic from the above article, this time not to count but to actually construct the trees.
Algorithm
Let's pick up number i
out of the sequence 1 ..n
and use it as the root of the current tree. Then there are i - 1
elements available for the construction of the left subtree and n - i
elements available for the right subtree. As we already discussed that results in G(i - 1)
different left subtrees and G(n - i)
different right subtrees, where G
is a Catalan number.
Now let's repeat the step above for the sequence 1 ... i - 1
to construct all left subtrees, and then for the sequence i + 1 ... n
to construct all right subtrees.
This way we have a root i
and two lists for the possible left and right subtrees. The final step is to loop over both lists to link left and right subtrees to the root.
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def generate_trees(start, end):
if start > end:
return [None,]
all_trees = []
for i in range(start, end + 1): # pick up a root
# all possible left subtrees if i is choosen to be a root
left_trees = generate_trees(start, i - 1)
# all possible right subtrees if i is choosen to be a root
right_trees = generate_trees(i + 1, end)
# connect left and right subtrees to the root i
for l in left_trees:
for r in right_trees:
current_tree = TreeNode(i)
current_tree.left = l
current_tree.right = r
all_trees.append(current_tree)
return all_trees
return generate_trees(1, n) if n else []