Leetcode 95. Unique Binary Search Trees II

在这里插入图片描述
方法1: recursion。我们随机从1-n中选一个数字作为root节点。然后左右两边分别recursion,算出左右子树所有的可能情况,然后与当前root节点排列组合得到所有可能情况。时间复杂2^n,空间复杂2 ^n。

/**
 * 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) {
        return genTrees(1, n);
    }
    
    public List<TreeNode> genTrees(int start, int end){
        List<TreeNode> list = new ArrayList<>();
        if(start == end){
            list.add(new TreeNode(start));
            return list;
        }
        if(start > end) return list;
        for(int i = start; i <= end; i++){
            TreeNode mid = new TreeNode(i);
            List<TreeNode> lefts = genTrees(start, i-1);
            List<TreeNode> rights = genTrees(i+1, end);
            List<TreeNode> res = constructTrees(mid, lefts, rights);
            for(TreeNode node : res) list.add(node);
        }
        return list;
    }
    public List<TreeNode> constructTrees(TreeNode mid, List<TreeNode> lefts, List<TreeNode> rights){
        List<TreeNode> list = new ArrayList<TreeNode>();
        if(lefts.size() == 0){
            for(TreeNode node : rights){
                TreeNode copy = new TreeNode(mid.val);
                copy.right = node;
                list.add(copy);
            }
        }else if(rights.size() == 0){
            for(TreeNode node : lefts){
                TreeNode copy = new TreeNode(mid.val);
                copy.left = node;
                list.add(copy);
            }
        }else{
           for(TreeNode left : lefts){
                for(TreeNode right : rights){
                    TreeNode copy = new TreeNode(mid.val);
                    copy.left = left;
                    copy.right = right;
                    list.add(copy);
                }
            } 
        }
        return list;
    }
}

总结:

  • 这道题目还可以优化,就是用dp来优化,但是我还没做到dp题,所以现在先放一下。
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页