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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题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的主要内容,如果未能解决你的问题,请参考以下文章

经典面试算法题:线性查找有序二维数组

记某公司面试算法题:查找一个有序数组某个数字出现的次数

记某公司面试算法题:查找一个有序数组某个数字出现的次数

精选力扣500题 第22题 LeetCode 88. 合并两个有序数组c++详细题解

面试题:2个有序数组变为一个有序数组

一道微软面试题:“半”有序数组如何进行二分查找?