95. Unique Binary Search Trees II 不同bst的个数

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

 

Example 1:

95. Unique Binary Search Trees II 不同bst的个数

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

就是生成东西的题,用dc

参考:https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31600/Quite-clean-Java-solution-with-explanation

public class Solution {
    public List<TreeNode> generateTrees(int n) {
        if(n == 0)
            return new ArrayList<TreeNode>();
        return generateTrees(1, n);
    }
    
    List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> result = new ArrayList<TreeNode>();
        if(start > end) {
            result.add(null);
            return result;
        }
        for(int i = start; i <= end; i++) {
            List<TreeNode> leftSubTrees = generateTrees(start, i - 1);
            List<TreeNode> rightSubTrees = generateTrees(i + 1, end);
       //左右每个点都遍历到 for(TreeNode left : leftSubTrees) { for(TreeNode right : rightSubTrees) { TreeNode root = new TreeNode(i); root.left = left; root.right = right; result.add(root); } } } return result; } }

 

 
上一篇:利用U盘制作Win To Go


下一篇:AcWing 8.二维费用的背包问题