码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-95-Unique Binary Search Trees II]

时间:2017-06-17 22:39:58      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:bsp   linked   integer   variant   思路   and   ram   win   turn   

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

 

 

思路:

This problem is a variant of the problem of Unique Binary Search Trees.

I provided a solution along with explanation for the above problem, in the question "DP solution in 6 lines with explanation"

It is intuitive to solve this problem by following the same algorithm. Here is the code in a divide-and-conquer style.

public List<TreeNode> generateTrees(int n) {
    return generateSubtrees(1, n);
}

private List<TreeNode> generateSubtrees(int s, int e) {
    List<TreeNode> res = new LinkedList<TreeNode>();
    if (s > e) {
        res.add(null); // empty tree
        return res;
    }

    for (int i = s; i <= e; ++i) {
        List<TreeNode> leftSubtrees = generateSubtrees(s, i - 1);
        List<TreeNode> rightSubtrees = generateSubtrees(i + 1, e);

        for (TreeNode left : leftSubtrees) {
            for (TreeNode right : rightSubtrees) {
                TreeNode root = new TreeNode(i);
                root.left = left;
                root.right = right;
                res.add(root);
            }
        }
    }
    return res;
}

参考:

https://discuss.leetcode.com/topic/8410/divide-and-conquer-f-i-g-i-1-g-n-i

[leetcode-95-Unique Binary Search Trees II]

标签:bsp   linked   integer   variant   思路   and   ram   win   turn   

原文地址:http://www.cnblogs.com/hellowooorld/p/7041448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!