LeetCode OJ 95. Unique Binary Search Trees II

时间:2022-01-15 18:26:26

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.

这道题目要求构建出存储1...n的所有平衡二叉树,并且这些树是相互独立的,如果有M棵树,那么每个节点都要被new M次。我的想法就是遍历1~n,构建出每一个数字作为根节点时它的左子树和右子树,然后根节点加所有左右子树的组合就是我们要构建的BST。很明显这是递归的思想,代码如下:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<TreeNode> list = new ArrayList();
public List<TreeNode> generateTrees(int n) {
if(n<=0) return list;
list = trees(1, n);
return list;
} public List<TreeNode> trees(int n, int m){ //构建BST
List<TreeNode> clist = new ArrayList();
if(m<n){
clist.add(null);
return clist;
}
if(m==n){
TreeNode node = new TreeNode(n);
clist.add(node);
return clist;
}
for(int i = n; i<=m; i++){
List<TreeNode> llist = trees(n, i-1);//构建所有的左子树
List<TreeNode> rlist = trees(i+1, m);//构建所有的右子树
for(TreeNode lnode:llist){ //生成以i为根节点的所有BST
for(TreeNode rnode:rlist){
TreeNode root = new TreeNode(i);
root.left = copyTree(lnode);
root.right = copyTree(rnode);
clist.add(root);
}
}
}
return clist;
} public TreeNode copyTree(TreeNode root){ //复制二叉树
if(root==null) return null;
else{
TreeNode croot = new TreeNode(root.val);
croot.left = copyTree(root.left);
croot.right = copyTree(root.right);
return croot;
}
}
}