Leetcode 95. Unique Binary Search Trees II

Posted zhangwj0101

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 95. Unique Binary Search Trees II相关的知识,希望对你有一定的参考价值。

Question

Given 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

Code

public List<TreeNode> get(int left, int right) 
        List<TreeNode> res = new ArrayList<>();
        if (left <= right) 
            for (int i = left; i <= right; i++) 
                List<TreeNode> l = get(left, i - 1);
                List<TreeNode> r = get(i + 1, right);
                for (TreeNode ll : l) 
                    for (TreeNode lr : r) 
                        TreeNode s = new TreeNode(i);
                        s.left = ll;
                        s.right = lr;
                        res.add(s);
                    
                
            

         else 
            res.add(null);
        
        return res;
    

    public List<TreeNode> generateTrees(int n) 
        if (n == 0) 
            return new ArrayList<>();
        
        return get(1, n);
    

以上是关于Leetcode 95. Unique Binary Search Trees II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 95. Unique Binary Search Trees II

LeetCode 95. Unique Binary Search Trees II

[leetcode-95-Unique Binary Search Trees II]

leetcode95 Unique Binary Search Trees II

leetcode [95]Unique Binary Search Trees II

[LeetCode] 95. Unique Binary Search Trees II