problem:
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.
thinking:
(1)
这道题是求解所有可行的二叉查找树,从Unique Binary Search Trees中我们已经知道,可行的二叉查找树的数量是相应的卡特兰数,不是一个多项式时间的数量级,所以我们要求解所有的树,自然是不能多项式时间内完成的了。算法上还是用求解NP问题的方法来求解,也就是N-Queens中 介绍的在循环中调用递归函数求解子问题。思路是每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取 然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况),构造好之后作为当前树的 结果返回。 (2)提示使用DP,实际上使用的是DFS深搜(回溯)。
(3)
这道题的解题依据是:
当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性: 以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。
code:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
return dfs(1,n) ;
}
protected:
vector<TreeNode*> dfs(int begin, int end)
{
vector<TreeNode*> ret;
if(begin>end)
{
ret.push_back(NULL);
return ret;
}
for(int i=begin;i<=end;i++)
{
vector<TreeNode*> lefttree = dfs(begin,i-1);
vector<TreeNode*> righttree = dfs(i+1,end);
for(int m=0;m<lefttree.size();m++)
for(int n=0;n<righttree.size();n++)
{
TreeNode *tmp = new TreeNode(i);
ret.push_back(tmp);
tmp->left=lefttree[m];
tmp->right=righttree[n];
}
}
return ret;
}
};leetcode || 95、Unique Binary Search Trees II
原文地址:http://blog.csdn.net/hustyangju/article/details/45071153