【Leetcode】Unique Binary Search Trees II

题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/
题目:

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

思路:

当根结点分别为1~n时,递归遍历,根结点大于左子树小于右子树。

算法:

public List<TreeNode> generateTrees(int n) {  
        if (n == 0)  
            return null;  
        return dsp(1, n);  
    }  
  
    public List<TreeNode> dsp(int start, int end) {  
        List<TreeNode> res = new ArrayList<TreeNode>();  
        if (start > end) {  
            res.add(null);  
            return res;  
        }  
  
        for (int i = start; i <= end; i++) {  
            List<TreeNode> left = dsp(start, i - 1);  
            List<TreeNode> right = dsp(i + 1, end);  
            for (TreeNode l : left) {  
                for (TreeNode r : right) {  
                    TreeNode root = new TreeNode(i);  
                    root.left = l;  
                    root.right = r;  
                    res.add(root);  
                }  
            }  
        }  
        return res;  
    }  


你可能感兴趣的:(【Leetcode】Unique Binary Search Trees II)