给定结点数n,结点值为1,2,...,n,求由这些结点可以构成的所有二叉查找树。
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
思路:递归构造,分别构造出左,右子树,然后组合成来。
- /**
- * 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 generateTrees(1,n);
- }
- vector<TreeNode *> generateTrees(int start, int end)
- {
- vector<TreeNode *> trees;
- if (start > end)
- {
- trees.push_back(NULL);
- return trees;
- }
- if (start==end)
- {
- trees.push_back(new TreeNode(start));
- return trees;
- }
- for (int i=start; i<=end; ++i)
- {
- vector<TreeNode *> treesleft = generateTrees(start,i-1);
- vector<TreeNode *> treesright = generateTrees(i+1,end);
- for (size_t j=0; j<treesleft.size(); ++j)
- {
- for (size_t k=0; k<treesright.size(); ++k)
- {
- TreeNode *root = new TreeNode(i);
- root->left = treesleft[j];
- root->right = treesright[k];
- trees.push_back(root);
- }
- }
- }
- return trees;
- }
- };
- from:http://blog.csdn.net/zjull/article/details/11712071