- Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
my thoughts:
1. recursion
my solution:
**********72ms
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def genTree(start, end):
res = []
if start == end:
return None
for i in range(start, end):
#print(i, start, end)
left = genTree(start, i)
right = genTree(i+1, end)
for lt in left or [None]:
for rt in right or [None]:
root = TreeNode(i)
root.left, root.right = lt, rt
res.append(root)
return res
return genTree( 1, n+1 ) or []
my comments:
from other ppl's solution:
1. N/A