Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
输出1~n能生成的所有BST。
首先是BST的生成方法。根据BST的特性(若有左子树,值必然小于根;若有右子树,值必然大于根)。对于1,2,...,n,任意选择一个数k作为根节点,1,2,...,k-1构成了它的左子树,k+1,k+2,...,n构成了右子树,左右子树的生成方法以此类推。
根据上面的分析,可以很快想到用循环递归做。考虑到其中有许多重复计算部分,可以用增加一个记录。
因为unordered_map是基于哈希表的,不能用pair<int, int>之类的自定义key,这边就用string来记录起点和终点。
如果想用pair<int, int>,可以用map来做。
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 unordered_map<string, vector<TreeNode*>> subtree; 12 public: 13 vector<TreeNode*> helper(int low, int high) { 14 vector<TreeNode*> vt; 15 for (int i = low; i <= high; ++i) { 16 vector<TreeNode*> lt{nullptr}; 17 vector<TreeNode*> rt{nullptr}; 18 if (low <= i - 1) { 19 string s = to_string(low) + " " + to_string(i - 1); 20 lt = subtree.find(s) == subtree.end()? helper(low, i - 1): subtree[s]; 21 } 22 if (i + 1 <= high) { 23 string s = to_string(i + 1) + " " + to_string(high); 24 rt = subtree.find(s) == subtree.end()? helper(i + 1, high): subtree[s]; 25 } 26 for (auto &l: lt) 27 for (auto &r: rt) { 28 TreeNode* root = new TreeNode(i); 29 root->left = l; 30 root->right = r; 31 vt.push_back(root); 32 } 33 } 34 string index = to_string(low) + " " + to_string(high); 35 subtree[index] = vt; 36 return vt; 37 } 38 vector<TreeNode*> generateTrees(int n) { 39 return helper(1, n); 40 } 41 };