95 unique binary search trees ii

Best Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def (self, n):

if n == 0:
return []
return self.dfs(1, n)

def dfs(self, start, end):
if start > end: return [None]
res = []
for rootval in range(start, end+1):
LeftTree = self.dfs(start, rootval-1)
RightTree = self.dfs(rootval+1, end)
for i in LeftTree:
for j in RightTree:
root = TreeNode(rootval)
root.left = i
root.right = j
res.append(root)
return res

Time Complexity: O(2^n)
Space Complexity: O(2^n)