题目:
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代码:
class Solution { public: vector<TreeNode *> generateTrees(int n) { vector<TreeNode*> v; if(n<=0)return v; return GenerateSubTree(1, n + 1); } vector<TreeNode*> GenerateSubTree(int l, int r) { vector<TreeNode *> subTree; if (l >= r) { subTree.push_back(NULL); return subTree; } if (l == r - 1) { subTree.push_back(new TreeNode(l)); return subTree; } for (int i = l; i < r; ++i) { vector<TreeNode *> leftSubTree = GenerateSubTree(l, i); vector<TreeNode *> rightSubTree = GenerateSubTree(i + 1, r); for (int m = 0; m < leftSubTree.size(); ++m) { for (int n = 0; n < rightSubTree.size(); ++n) { TreeNode *root = new TreeNode(i); root->left = leftSubTree[m]; root->right = rightSubTree[n]; subTree.push_back(root); } } } return subTree; } };想法:多多拓展思路,采用递归法