95. Unique Binary Search Trees II

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

For example,
Given n = 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

一刷
题解:
借用discuss里面的解,希望二刷时能再弄清楚一些。
方法是 - 从1至n遍历数字时,每次把所有数字分为三部分, 当前数字,比当前数字小的部分,以及比当前数字大的部分, 使用新的list分别存储这两部分。从左部和右部分别按顺序取值,和当前i一起组合起来,成为当前i的一个解,当左右两部分遍历完毕以后,就得到了当前i的所有解。接着计算下一个i的解集。

Time Complexity - O(2n), Space Complexity - O(2n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
         if(n == 0) return new ArrayList<TreeNode>();
        return generateTrees(1, n);
    }
    
    private List<TreeNode> generateTrees(int lo, int hi){
        List<TreeNode> res = new ArrayList<>();
        if(lo > hi){
            res.add(null);
            return res;
        }
        
        for(int i=lo; i<=hi; i++){
            List<TreeNode> ll = generateTrees(lo, i-1);
            List<TreeNode> rr = generateTrees(i+1, hi);
            for(TreeNode l : ll){
                for(TreeNode r : rr){
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    res.add(root);
                }
            }
        }
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容