Description:
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
Example:
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
Link:
https://leetcode.com/problems/unique-binary-search-trees-ii/description/
解题方法:
用递归做:
返回值和参数:规定一个范围left和right(最开始范围为1和n),递归函数从范围中选择一个数作为当前树的根节点。这个数的左边范围为根节点的左子树,右边范围为根节点的右子树。最后将这些节点的集合作为返回值。
函数出口:当left > right时,返回一个只有NULL节点的集合。
函数体:每次从左右范围递归的集合结果各自取一个作为当前根节点的左右孩子
Time Complexity:
O(N^2)
完整代码:
vector<TreeNode*> generateTrees(int n)
{
if(!n)
return vector<TreeNode*>();
return helper(1, n);
}
vector<TreeNode*> helper(int left, int right)
{
vector<TreeNode*> result;
if(left > right)
{
result.push_back(NULL);
return result;
}
for(int i = left; i <= right; i++)
{
vector<TreeNode*> leftChild = helper(left, i - 1);
vector<TreeNode*> rightChild = helper(i + 1, right);
for(auto a: leftChild)
{
for(auto b: rightChild)
{
TreeNode* curr = new TreeNode(i);
curr->left = a;
curr->right = b;
result.push_back(curr);
}
}
}
return result;
}