LeetCode 95. Unique Binary Search Trees II
95. Unique Binary Search Trees II
相关链接
描述
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类;
假设要生成根节点为i的所有BST,可以先生成(0 到 i-1)的所有左子树和(i+1到n)的所有右子树,然后两两组合;
/**
* Definition for a binary tree node.
* 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) {
vector<TreeNode*> tree;
if (n == 0)
return tree;
dfs(1, n, tree);
return tree;
}
void dfs(int start, int end, vector<TreeNode*> &tree)
{
if (start > end)
{
tree.push_back(NULL);
}
for(int i = start; i <= end; i++){
vector<TreeNode*> left;
vector<TreeNode*> right;
dfs(start, i-1, left);
dfs(i+1, end, right);
for(int k = 0; k < left.size(); k++)
for(int j = 0; j < right.size(); j++)
{
TreeNode * root = new TreeNode(i);
root->left = left[k];
root->right = right[j];
tree.push_back(root);
}
}
};
参考
csdn
blogs record our growth