Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

    Example:

    1. Input: 3
    2. Output:
    3. [
    4. [1,null,3,2],
    5. [3,2,null,1],
    6. [3,1,null,null,2],
    7. [2,1,3],
    8. [1,null,2,null,3]
    9. ]
    10. Explanation:
    11. The above output corresponds to the 5 unique BST's shown below:
    12. 1 3 3 2 1
    13. \ / / / \ \
    14. 3 2 1 1 3 2
    15. / / \ \
    16. 2 1 2 3

    题意

    给定n个整数1,2,…,n,用这些整数构成二叉搜索树BST的结点。返回所有可以形成的BST。

    思路

    96. Unique Binary Search Trees 威力加强版。同样的思想,每次固定一个根结点,生成所有可能的BST。利用分治法和递归进行处理。


    代码实现

    1. class Solution {
    2. public List<TreeNode> generateTrees(int n) {
    3. if (n == 0) {
    4. return new ArrayList<>();
    5. }
    6. return solve(1, n);
    7. }
    8. private List<TreeNode> solve(int start, int end) {
    9. List<TreeNode> list = new ArrayList<>();
    10. if (start > end) {
    11. list.add(null);
    12. }
    13. for (int i = start; i <= end; i++) {
    14. List<TreeNode> left = solve(start, i - 1);
    15. List<TreeNode> right = solve(i + 1, end);
    16. for (TreeNode p : left) {
    17. for (TreeNode q : right) {
    18. TreeNode root = new TreeNode(i);
    19. root.left = p;
    20. root.right = q;
    21. list.add(root);
    22. }
    23. }
    24. }
    25. return list;
    26. }
    27. }