【leetcode刷题笔记】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

题解:递归的枚举1~n的每个节点为根节点,然后递归的利用它左边的节点构造左子树,放在一个list里面;再利用它右边的节点构造右子树,也放在一个list里面;最终枚举两个list里面的左子树和右子树,构建一棵树。

代码如下:

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; left = null; right = null; }
* }
*/
public class Solution {
private ArrayList<TreeNode> generate(int start,int end){
ArrayList<TreeNode> answer = new ArrayList<TreeNode>();
if(start > end){
answer.add(null);
return answer;
} //for every node from start to right,make it as tree root and recursively build its left and right child tree
for(int i = start; i <= end;i++){
ArrayList<TreeNode> left = generate(start, i-1);
ArrayList<TreeNode> right = generate(i+1, end);
for(TreeNode l:left){
for(TreeNode r:right){
TreeNode root = new TreeNode(i);
root.left = l;
root.right = r;
answer.add(root);
}
} } return answer; }
public List<TreeNode> generateTrees(int n) {
return generate(1,n);
}
}
上一篇:BZOJ 1208: [HNOI2004]宠物收养所 SET的妙用


下一篇:BZOJ 1208 [HNOI2004]宠物收养所:Splay(伸展树)