您的位置:首页 > 产品设计 > UI/UE

95. Unique Binary Search Trees II

2018-01-23 20:26 357 查看
Given an integer 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..n是任何BST节点1到n的有序遍历。

所以如果我选择第i个节点作为我的根,左子树将包含元素1到(i-1),右子树将包含元素(i + 1)到n。

我使用递归调用来找回所有可能的左树子树和右树子树,并将它们以各种可能的方式与根结合起来。

1 class Solution {
2     public List<TreeNode> generateTrees(int n) {
3         if (n<1) return new ArrayList<TreeNode>();
4         return gen(1,n);
5     }
6     private List<TreeNode> gen(int start,int end){
7         List<TreeNode> res = new ArrayList<TreeNode>();
8         if(start>end){ //越界
9             res.add(null);
10             return res;
11         }
12         if(start==end){ //只有一个点 gen(2,2)
13             res.add(new TreeNode(start));
14             return res;
15         }
16         List<TreeNode> left,right;
17         for(int i = start;i<=end;i++){
18             left = gen(start,i-1);
19             right = gen(i+1,end);
20             for(TreeNode l :left){
21                 for(TreeNode r:right){
22                     TreeNode root = new TreeNode(i);
23                     root.left=l;
24                     root.right=r;
25                     res.add(root);
26                 }
27             }
28         }
29          return res;
30     }
31 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: