Posted on 2014-01-12 15:30
Uriel 阅读(125)
评论(0) 编辑 收藏 引用 所属分类:
LeetCode
这题跟Unique Binary Search Trees一样,不过还要输出所有可能的树的每一个节点信息,用递归的方式写比较方便
对vector还很不熟练啊...写晕了之后还是参考了一下别人的代码
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 *> sov(int l, int r) {
13 vector<TreeNode *> ans;
14 if(l > r) ans.push_back(NULL);
15 else {
16 for(int i = l; i <= r; ++i) {
17 vector<TreeNode *> left = sov(l, i - 1);
18 vector<TreeNode *> right = sov(i + 1, r);
19 for(int ll = 0; ll < left.size(); ++ll) {
20 for(int rr = 0; rr < right.size(); ++rr) {
21 TreeNode *root = new TreeNode(i);
22 root->left = left[ll];
23 root->right = right[rr];
24 ans.push_back(root);
25 }
26 }
27 }
28 }
29 return ans;
30 }
31
32 vector<TreeNode *> generateTrees(int n) {
33 return sov(1, n);
34 }
35 };