[leetcode]Unique Binary Search Trees II

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 

算法思路:

分治法:求出左子树的list和右子树的list,然后循环两个子树,分别插入root的左右子树。

代码如下:

 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 buildTree(1,n);
13     }
14     private List<TreeNode> buildTree(int begin,int end){
15         List<TreeNode> res = new ArrayList<TreeNode>();
16         if(begin > end){
17             res.add(null);
18             return res;
19         }
20         List<TreeNode> left = new ArrayList<TreeNode>();
21         List<TreeNode> right = new ArrayList<TreeNode>();
22         for(int i = begin; i <= end; i++){
         //TreeNode node = new TreeNode(i); 本来这句写在这里,结果发现错鸟,大家可以脑补一下原因
23 left = buildTree(begin, i - 1); 24 right = buildTree(i + 1, end); 25 for(int j = 0; j < left.size(); j++){ 26 for(int k = 0; k < right.size(); k++){ 27 TreeNode node = new TreeNode(i); 28 node.left = left.get(j); 29 node.right = right.get(k); 30 res.add(node); 31 } 32 } 33 } 34 return res; 35 } 36 }

参考:

http://www.cnblogs.com/cheapcrook/archive/2013/01/29/2880903.html

 

posted on 2014-08-15 22:55  喵星人与汪星人  阅读(281)  评论(0编辑  收藏  举报