标签:example int 题目 add list 回溯 new t out i+1
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到n这n个数字,返回集合,集合中存放所有可能二叉搜索树的根节点。
解法:
我有想到使用回溯法做,但是并没有想到怎么使用回溯法。参考了网上的解法,当给定了n个数字时,根节点有1到n种可能,回溯的得到左右子树可能的结构,将根节点和左右子树相连便可以得到。
java:
class Solution {
public List<TreeNode>genTrees(int start,int end){
List<TreeNode>list=new ArrayList<TreeNode>();
if(start>end){
list.add(null);
return list;
}
if(start==end){
list.add(new TreeNode(start));
return list;
}
List<TreeNode>left,right;
for(int i=start;i<=end;i++){
left=genTrees(start,i-1);
right=genTrees(i+1,end);
for(TreeNode ln:left){
for(TreeNode rn:right){
TreeNode root=new TreeNode(i);
root.left=ln;
root.right=rn;
list.add(root);
}
}
}
return list;
}
public List<TreeNode> generateTrees(int n) {
if(n==0) return new ArrayList<TreeNode>();
return genTrees(1,n);
}
}
leetcode [95]Unique Binary Search Trees II
标签:example int 题目 add list 回溯 new t out i+1
原文地址:https://www.cnblogs.com/xiaobaituyun/p/10684898.html