Leetcode-95-不同的二叉搜索树Ⅱ 发表于 2020-07-21 | 分类于 Leetcode 题目 给定一个整数 n,生成所有由 1 … n 为节点所组成的 二叉搜索树 递归遍历1...n中的所有元素, 以当前元素为根结点. 计算所有可能的左子树和右子树, 并将所有左子树-右子树组合拼接到根结点上. 代码如下 1234567891011121314151617181920212223242526272829303132333435363738394041424344/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */class Solution { public List<TreeNode> generateTrees(int n) { if (n == 0) { return new ArrayList<TreeNode>(); } return generateTrees(1, n); } public List<TreeNode> generateTrees(int start, int end) { ArrayList<TreeNode> roots = new ArrayList<>(); if (start > end) { roots.add(null); return roots; } for (int i = start; i <= end; i++) { List<TreeNode> leftTrees = generateTrees(start, i - 1); // 获取所有可能的左子树 List<TreeNode> rightTrees = generateTrees(i + 1, end); // 获取所有可能的右子树 // 遍历所有左子树和右子树的组合, 拼接到根结点上 for (TreeNode leftTree : leftTrees) { for (TreeNode rightTree : rightTrees) { TreeNode root = new TreeNode(i, leftTree, rightTree); roots.add(root); } } } return roots; }}