Leetcode 95.不同的二叉搜索树II
不同的二叉搜索树2
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
示例:
输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
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 vector<TreeNode *> ret; 14 if (n == 0) 15 return ret; 16 return Helper(1, n); 17 } 18 vector<TreeNode *> Helper(int begin, int end) 19 { 20 vector<TreeNode *> ret; 21 if (begin > end) 22 ret.push_back(NULL); 23 else if (begin == end) 24 { 25 TreeNode* node = new TreeNode(begin); 26 ret.push_back(node); 27 } 28 else 29 { 30 for (int i = begin; i <= end; i++) 31 {//root 32 vector<TreeNode *> left = Helper(begin, i - 1); 33 vector<TreeNode *> right = Helper(i + 1, end); 34 for (int l = 0; l < left.size(); l++) 35 { 36 for (int r = 0; r < right.size(); r++) 37 { 38 //new tree 39 TreeNode* root = new TreeNode(i); 40 root->left = left[l]; 41 root->right = right[r]; 42 ret.push_back(root); 43 } 44 } 45 } 46 } 47 return ret; 48 } 49 };