Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
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
分析:
方法一:采用深度搜索方法,由于要构建二叉搜索树,很显然,我们把1,2,,,n. 当成一个数组来看,对于当前元素,数组左侧元素即为其左子树的元素,数组右侧元素为其右子树元素,采用深度搜索方式即可求得所有二叉搜索树。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
List<TreeNode> ans=new ArrayList<>();
if(n==0){
return ans;
}
helper(1,n,ans);
return ans;
}
private void helper(int start,int end,List<TreeNode> ans){
if(start>end){
ans.add(null);
return;
}
for(int i=start;i<=end;i++){
List<TreeNode> left=new ArrayList<>();
List<TreeNode> right=new ArrayList<>();
helper(start,i-1,left);
helper(i+1,end,right);
for(int j=0;j<left.size();j++){
for(int k=0;k<right.size();k++){
TreeNode root=new TreeNode(i);
root.left=left.get(j);
root.right=right.get(k);
ans.add(root);
}
}
}
}
}

本文介绍了一种使用深度优先搜索算法生成从1到n的所有唯一二叉搜索树的方法。通过将数值视为数组,左侧元素构成左子树,右侧元素构成右子树,递归地构建所有可能的二叉搜索树。
438

被折叠的 条评论
为什么被折叠?



