题目描述:
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
生成唯一的搜索二叉树。
思路:
要对n生成搜索二叉树,考虑:
从1到n的每一个数i,i∈[1,n],对于i,左子树的每个节点的范围是[1,i-1];右子树的每个节点的范围是[i+1,n]。
将左子树节点集Sl和右子树节点集Sr进行交叉遍历,与当前节点构成一个数。
本题是一个分治问题。
实现代码:
/**
* 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 List<TreeNode> GenerateTrees(int n)
{
return GenerateTrees(1, n);
}
public List<TreeNode> GenerateTrees(int start, int end)
{
List<TreeNode> list = new List<TreeNode>();
if (start > end) {
list.Add(null);
return list;
}
for (int i = start; i <= end; i++) {
List<TreeNode> lefts = GenerateTrees(start, i - 1);
List<TreeNode> rights = GenerateTrees(i + 1, end);
foreach (TreeNode left in lefts) {
foreach (TreeNode right in rights) {
TreeNode node = new TreeNode(i);
node.left = left;
node.right = right;
list.Add(node);
}
}
}
return list;
}
}