[Leetcode] Unique Binary Search Trees II

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

哎,WA了两次,因为把root = new TreeNode(i)放错了位置,这句应该放在最里面的循环里。因为每次都要新生成一棵树!

 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 st, int ed) {
13         vector<TreeNode *> res;
14         TreeNode *root = NULL;
15         if (st > ed) {
16             res.push_back(root);
17             return res;
18         }
19         vector<TreeNode *> left;
20         vector<TreeNode *> right;
21         for (int i = st; i <= ed; ++i) {
22             left = generateTrees(st, i - 1);
23             right = generateTrees(i + 1, ed);
24             for (int j = 0; j < left.size(); ++j) {
25                 for (int k = 0; k < right.size(); ++k) {
26                     root = new TreeNode(i);
27                     root->left = left[j];
28                     root->right = right[k];
29                     res.push_back(root);
30                 }
31             }
32         }
33         return res;
34     }
35     
36     vector<TreeNode *> generateTrees(int n) {
37         return generateTrees(1, n);
38     }
39 };

 

posted @ 2014-04-10 15:15  Eason Liu  阅读(1969)  评论(0编辑  收藏  举报