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

LeetCode Unique Binary Search Trees II

时间:2015-01-28 23:56:50      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

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 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; left = null; right = null; }
 8  * }
 9  */
10 public class Solution {
11      public List<TreeNode> generateTrees(int n) {
12          return create(1, n);
13      }
14 
15      List<TreeNode> create(int start,int end) {
16          List<TreeNode> results = new ArrayList<TreeNode>();
17          if (start > end) {
18              results.add(null);
19              return results;
20          }
21 
22          for (int k = start; k <= end; k++) {
23              List<TreeNode> left = create(start, k - 1);
24              List<TreeNode> right = create(k + 1, end);
25              for (int i = 0; i < left.size(); i++) {
26                  for (int j = 0; j < right.size(); j++) {
27                      TreeNode root = new TreeNode(k);
28                      root.left = left.get(i);
29                      root.right = right.get(j);
30                      results.add(root);
31                  }
32              }
33          }
34          return results;
35      }
36 }

 

LeetCode Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4257419.html

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