程序媛詹妮弗
终身学习

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

 

题意:

给定n个节点,列举可形成的不同的BST集合

 

思路:

跟 [leetcode]96. Unique Binary Search Trees给定节点形成不同BST的个数 相似。

对于给定的n

需要去查[1, n]范围内可生成的BST,如下图,

 

1       1           2          3       3   ...          i              ... n 
  \       \         / \        /       /            /      \  
   3       2       1   3      2       1      [1,i-1]     [i+1,n]
  /         \                /         \
2            3              1           2

我们需要列出

以1为root可生成的所有BST

以2为root可生成的所有BST

......

那么对于任意以 i 为root可生成的所有BST,根据BST的性质:

其左子树的值一定小于i,也就是[1, i - 1]区间,用helper生成list of leftList

而右子树的值一定大于i,也就是[i + 1, n]区间, 用helper生成list of rightList

 

最后,用root,  leftList中的值,rightList中的值,三者生成BST

 

代码:

 1 class Solution {
 2     public List<TreeNode> generateTrees(int n) {
 3         if(n == 0) return new ArrayList<>();
 4         return helper(1, n);  // root node from 1 to n   
 5     }
 6     
 7     private List<TreeNode> helper(int left, int right){
 8         List<TreeNode> result = new ArrayList<>();
 9         if(left > right){
10             result.add (null);
11             return result;
12         }
13         for(int i = left; i <= right; i++){
14             List<TreeNode> lefts = helper(left, i-1);
15             List<TreeNode> rights = helper(i+1, right);
16             for(TreeNode l : lefts){
17                 for(TreeNode r : rights){
18                     TreeNode root = new TreeNode(i); 
19                     root.left = l;
20                     root.right = r;
21                     result.add(root);
22                 }
23             }
24         }
25         return result;
26     } 
27 }

 

posted on 2018-05-30 05:07  程序媛詹妮弗  阅读(195)  评论(0编辑  收藏  举报