Unique Binary Search Trees II

Given an integer 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

 

Runtime: 28ms

 1 /**
 2  * Definition for a binary tree node.
 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* > result;
14         if(!n) return result;
15         return generateBST(1, n);
16     }
17     
18     vector<TreeNode* > generateBST(int low, int high) {
19         vector<TreeNode* > result;
20         if(low > high) {
21             result.push_back(NULL);
22             return result;
23         }
24         
25         for(int i = low; i <= high; i++) {
26             vector<TreeNode* > leftSubtree = generateBST(low, i - 1);
27             vector<TreeNode* > rightSubtree = generateBST(i + 1, high);
28             
29             for(int m = 0; m < leftSubtree.size(); m++) {
30                 for(int n = 0; n < rightSubtree.size(); n++) {
31                     TreeNode* root = new TreeNode(i);
32                     root->left = leftSubtree[m];
33                     root->right = rightSubtree[n];
34                     result.push_back(root);
35                 }
36             }
37         }
38         
39         return result;
40     }
41 };

 

posted @ 2016-08-07 06:01  amazingzoe  阅读(146)  评论(0编辑  收藏  举报