Given an integer n, return all the structurally unique BST’s (binary search trees), which has exactlynnodes of unique values from1ton. Return the answer in any order.
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]]
Constraints:
1 <= n <= 8
Test Cases
1 2 3 4 5 6 7 8
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: defgenerateTrees(self, n: int) -> List[Optional[TreeNode]]:
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from _utils.binary_tree import print_tree from solution import Solution from solution2 import Solution as Solution2
null = None
@pytest.mark.parametrize('n, expected', [ (3, [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]), (1, [[1]]), ]) @pytest.mark.parametrize('sol', [Solution(), Solution2()]) deftest_solution(sol, n, expected): result = sol.generateTrees(n) result = [print_tree(root) for root in result] result.sort() assert result == sorted(expected)
from functools import cache from itertools import product from typing importOptional
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defgenerateTrees(self, n: int) -> list[Optional[TreeNode]]: @cache defgen(i: int, j: int) -> list[TreeNode]: if i == j: return [TreeNode(i)] elif i > j: return [None]
trees = [] for k inrange(i, j + 1): left = gen(i, k - 1) right = gen(k + 1, j) for l, r in product(left, right): trees.append(TreeNode(k, l, r))
from itertools import product from typing importOptional
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defgenerateTrees(self, n: int) -> list[Optional[TreeNode]]: # dp[i][j]: all trees for i...j dp = [[[None] for _ inrange(n + 2)] for _ inrange(n + 2)] for size inrange(1, n + 1): for i inrange(1, n - size + 2): j = i + size - 1 trees = [] for k inrange(i, j + 1): for l, r in product(dp[i][k-1], dp[k+1][j]): trees.append(TreeNode(k, l, r))