【leetcode】Unique Binary Search Trees II

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

 

 
 
从1-n中选取一个元素i,i左边的元素都在左子树上,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 n) {
13        
14         vector<TreeNode *>result=build(1,n);
15         return result;
16     }
17    
18     vector<TreeNode *> build(int l,int r)
19     {
20        
21         if(l>r)
22         {
23             vector<TreeNode *> root(1);
24             root[0]=NULL;
25             return root;
26         }
27        
28         vector<TreeNode *> result;
29        
30         for(int i=l;i<=r;i++)
31         {
32             vector<TreeNode *> left=build(l,i-1);
33             vector<TreeNode *> right=build(i+1,r);
34             for(int j=0;j<left.size();j++)
35             {
36                 for(int k=0;k<right.size();k++)
37                 {
38                     TreeNode *root=new TreeNode(i);
39                     root->left=left[j];
40                     root->right=right[k];
41                     result.push_back(root);
42                    
43                 }
44             }
45         }
46        
47         return result;
48     }
49 };

 

posted @ 2015-01-11 14:28  H5开发技术  阅读(181)  评论(0编辑  收藏  举报