给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
示例:
输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
二叉搜索树:二叉树的所有节点满足:左节点值小于根节点,右结点值大于根节点。也就是说,它的中序遍历是递增的。
要构建1到n的二叉搜索树,可以使用递归的方法,遍历从1到n,分别递归构造出左子树和右子树,并储存在一个list中,在以i为根节点,将左子树与右子树连接起来,在将这层构造出的所有树返回给递归函数。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<TreeNode> newtree(int start,int end)
{
IList<TreeNode> trees=new List<TreeNode>();
//处理下标越界
if(start>end){
trees.Add(null);
return trees;
}
for(int i=start;i<=end;i++)
{
//储存左子树和右子树
IList<TreeNode> left=new List<TreeNode>();
IList<TreeNode> right=new List<TreeNode>();
//递归构造左子树和右子树
left=newtree(start,i-1);
right=newtree(i+1,end);
//将所有左子树,右子树连接起来
for(int j=0;j<left.Count;j++)
for(int k=0;k<right.Count;k++)
{
TreeNode root=new TreeNode(i);
root.left=left[j];
root.right=right[k];
trees.Add(root);
}
}
return trees;
}
public IList<TreeNode> GenerateTrees(int n)
{
IList<TreeNode> ans=new List<TreeNode>();
if(n==0)
return ans;
ans=newtree(1,n);
return ans;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。