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

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

Hide Tags Tree Dynamic Programming

SOLUTION 1:

使用递归来做。

1. 先定义递归的参数为左边界、右边界,即1到n.

2. 考虑从left, 到right 这n个数字中选取一个作为根,余下的使用递归来构造左右子树。 

3. 当无解时,应该返回一个null树,这样构造树的时候,我们会比较方便,不会出现左边解为空,或是右边解为空的情况。

4. 如果说左子树有n种组合,右子树有m种组合,那最终的组合数就是n*m. 把这所有的组合组装起来即可

 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         // 0.07
13         return dfs(1, n);
14     }
15     
16     public List<TreeNode> dfs(int left, int right) {
17         List<TreeNode> ret = new ArrayList<TreeNode>();
18         
19         // The base case;
20         if (left > right) {
21             ret.add(null);
22             return ret;
23         }
24         
25         for (int i = left; i <= right; i++) {
26             List<TreeNode> lTree = dfs(left, i - 1);
27             List<TreeNode> rTree = dfs(i + 1, right);
28             for (TreeNode nodeL: lTree) {
29                 for (TreeNode nodeR: rTree) {
30                     TreeNode root = new TreeNode(i);
31                     root.left = nodeL;
32                     root.right = nodeR;
33                     ret.add(root);
34                 }
35             }
36         }
37         
38         return ret;
39     }
40 }
View Code

 

CODE:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/72f914daab2fd9e2eb8a63e4643297d78d4fadaa/tree/GenerateTree2.java

posted on 2015-01-28 16:40  Yu's Garden  阅读(2305)  评论(0编辑  收藏

导航