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

Unique Binary Search Trees II 解答

时间:2015-09-21 06:58:04      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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 

Solution

Key to the solution is to divide the problem into two sub-problems. Unlike "Unique Binary Search Trees", this problem is NP-hard.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<TreeNode> generateTrees(int n) {
12         return generateTreesHelper(1, n); 
13     }
14     private List<TreeNode> generateTreesHelper(int start, int end) {
15         List<TreeNode> result = new ArrayList<TreeNode>();
16         if (start > end) {
17             result.add(null);
18             return result;
19         }
20         for (int i = start; i <= end; i++) {
21             List<TreeNode> lefts = generateTreesHelper(start, i - 1);
22             List<TreeNode> rights = generateTreesHelper(i + 1, end);
23             for (TreeNode left : lefts) {
24                 for (TreeNode right : rights) {
25                     TreeNode tmp = new TreeNode(i);
26                     tmp.left = left;
27                     tmp.right = right;
28                     result.add(tmp);
29                 }
30             }
31         }
32         return result;
33     }
34 }

 

Unique Binary Search Trees II 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4825083.html

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