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

[leetcode]Unique Binary Search Trees II

时间:2014-08-15 23:44:29      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   strong   for   ar   

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++){
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

 

[leetcode]Unique Binary Search Trees II,布布扣,bubuko.com

[leetcode]Unique Binary Search Trees II

标签:style   blog   http   color   io   strong   for   ar   

原文地址:http://www.cnblogs.com/huntfor/p/3915819.html

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