动态规划33(Leetcode95不同的二叉搜索树2)

代码:

1110-1

题解的答案 这也没有用dp吧?

/**
 * 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 generateTrees(int n) {
        if(n==0)return new LinkedList();
        return generateTrees(1,n);        

    }
    public List generateTrees(int start,int end){
        List allTrees = new LinkedList();
        if(start>end){
            allTrees.add(null);
            return allTrees;
        }
        for(int i=start;i<=end;i++){ //遍历根节点
            List leftTrees = generateTrees(start,i-1);
            List rightTrees = generateTrees(i+1,end);

            for(TreeNode left:leftTrees){
                for(TreeNode right: rightTrees){
                    TreeNode currTree = new TreeNode(i);
                    currTree.left = left;
                    currTree.right = right;
                    allTrees.add(currTree);
                }
            }
        }
        return allTrees;
    }
}

你可能感兴趣的:(动态规划,算法)