95. Unique Binary Search Trees II

Given an integern, generate all structurally uniqueBST's(binary search trees) that store values 1...n.

For example,
Givenn= 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

tag: recursion, DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) return new ArrayList<TreeNode>();
        return dfs(1, n);
    }

    private List<TreeNode> dfs(int start, int end){
        List<TreeNode> ans = new ArrayList<>();

        if (start > end){
            ans.add(null);
            return ans;
        }

        for (int i = start; i <= end; i++){
            List<TreeNode> leftList = dfs(start, i - 1);
            List<TreeNode> rightList = dfs(i + 1, end);

            for (TreeNode left : leftList){
                for (TreeNode right : rightList){
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    ans.add(root);
                }
            }
        }

        return ans;
    }
}

results for ""

    No results matching ""