-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0095-unique-binary-search-trees-ii.py
More file actions
34 lines (27 loc) · 971 Bytes
/
0095-unique-binary-search-trees-ii.py
File metadata and controls
34 lines (27 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Definition for a binary tree node.
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def allPossobleBST(self, start, end, memo):
res = []
if start > end:
res.append(None)
return res
if (start, end) in memo:
return memo[(start, end)]
for i in range(start, end+1):
leftSubTree = self.allPossobleBST(start, i - 1, memo)
rightSubTree = self.allPossobleBST(i + 1, end, memo)
for left in leftSubTree:
for right in rightSubTree:
root = TreeNode(i, left, right)
res.append(root)
memo[(start, end)] = res
return res
def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
memo = {}
return self.allPossobleBST(1, n, memo)