生成二叉查找树;
哎,思考了大半天才写出来,
主要卡在生成结点上了,开始没考虑好怎么把不同的树在不同的地方复制前面的部分,
还是对递归的使用不够成熟,理解和掌握的还不够好!
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode *> generateTrees(int n) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 vector<TreeNode *> res; 16 if (n <= 0) { 17 res.push_back(NULL); 18 return res; 19 } 20 generate(res, 1, n + 1); 21 return res; 22 } 23 void generate(vector<TreeNode *> &res, int l, int r) { 24 if (l == r) { 25 res.push_back(NULL); 26 return; 27 } 28 for (int i = l; i < r; ++i) { 29 vector<TreeNode *> leftres; 30 generate(leftres, l, i); 31 vector<TreeNode *> rightres; 32 generate(rightres, i + 1, r); 33 for (int j = 0; j < leftres.size(); ++j) { 34 for (int k = 0; k <rightres.size(); ++k) { 35 TreeNode *root = new TreeNode(i); 36 root->left = leftres[j]; 37 root->right = rightres[k]; 38 res.push_back(root); 39 } 40 } 41 } 42 } 43 };