首页 > 代码库 > 面试题22:有序数组生成BST

面试题22:有序数组生成BST

  1. 对于一个含有n个数的有序数组1~N,能够产生多少种不同结果的二叉搜素树BST?
  2. 如何生成这些不同结构的BST?
 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         int* dp = new int[n+1];
 5         dp[0] = 1;
 6         dp[1] = 1;
 7         dp[2] = 2;
 8         for(int i=3;i<=n;i++){
 9             dp[i] = 0;
10             for(int j=1;j<=i;j++){
11                 dp[i]+=dp[j-1]*dp[i-j];
12             }
13         }
14         return dp[n];
15     }
16 
17     int numTrees2(int n){
18         if(n==0) return 1;
19         if(n < 3) return n;
20         int sum = 0;
21         for(int i=1;i<=n;i++){
22             sum += numTrees2(i-1)*numTrees2(n-i);
23         }
24         return sum;
25     }
26 };
 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 
11 class Solution {
12 public:
13     vector<TreeNode *> generateTrees(int left, int right) {
14         vector<TreeNode*> res;
15         if (left > right) {
16             res.push_back(nullptr);
17             return res;
18         }
19         
20         if(left == right){
21             res.push_back(new TreeNode(left));
22             return res;
23         }
24 
25         for (int i = left; i <= right; i++) {
26             //TreeNode* root = new TreeNode(i);
27             vector<TreeNode*> leftRes = generateTrees(left, i-1);
28             vector<TreeNode*> rightRes = generateTrees(i + 1, right);
29             for (size_t j = 0; j < leftRes.size(); j++) {
30                 for (size_t k = 0; k < rightRes.size(); k++) {
31                     TreeNode* root = new TreeNode(i);
32                     root->left = leftRes[j];
33                     root->right = rightRes[k];
34                     res.push_back(root);
35                 }
36             }
37         }
38         return res;
39     }
40 
41     vector<TreeNode*> generateTrees(int n){
42         vector<TreeNode*> res;
43         if(n == 0) {
44             res.push_back(nullptr);
45             return res;
46         }
47         return generateTrees(1,n);
48     }
49 
50 };

 

面试题22:有序数组生成BST