leetcode - Unique Binary Search Trees II
2013-11-11 22:22 张汉生 阅读(116) 评论(0) 编辑 收藏 举报
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 min, int max){ 13 if (min>max){ 14 TreeNode * tmp = NULL; 15 return vector<TreeNode*>(1,tmp); 16 } 17 vector<TreeNode *> rlt; 18 for (int i=min; i<=max; i++){ 19 vector<TreeNode*> left_nodes = generateTrees(min, i-1); 20 int lsize = left_nodes.size(); 21 vector<TreeNode*> right_nodes = generateTrees(i+1,max); 22 int rsize = right_nodes.size(); 23 for (int j=0; j<lsize; j++) 24 for (int k=0; k<rsize; k++){ 25 TreeNode * node = new TreeNode(i); 26 node->left = left_nodes[j]; 27 node->right = right_nodes[k]; 28 rlt.push_back(node); 29 } 30 } 31 return rlt; 32 } 33 vector<TreeNode *> generateTrees(int n) { 34 // IMPORTANT: Please reset any member data you declared, as 35 // the same Solution instance will be reused for each test case. 36 return generateTrees(1,n); 37 } 38 };