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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
class Solution { private: vector<TreeNode *> res; public: vector<TreeNode *> generateTrees(int n) { res.clear(); res = dfs(1, n + 1); return res; } vector<TreeNode*> dfs(int start, int end) { vector<TreeNode*> res; if (start >= end) { res.push_back(NULL); return res; } TreeNode* rt = NULL; for (int i=start; i<end; i++) { vector<TreeNode*> lsub = dfs(start, i); vector<TreeNode*> rsub = dfs(i+1, end); for (int li=0; li<lsub.size(); li++) { for (int ri=0; ri<rsub.size(); ri++) { rt = new TreeNode(i); rt->left = lsub[li]; rt->right= rsub[ri]; res.push_back(rt); } } } return res; } };
递归真是个好东西!
第二轮:
写一个非递归的,不过感觉内存占用应该会大许多吧
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> generateTrees(int n) { unordered_map<long, vector<TreeNode*> > dp; dp.insert(make_pair(0, vector<TreeNode*>(1, NULL))); for (int k=0; k<=n; k++) { for (int i=0; (i + k) <= n; i++) { int from = i, to = i + k; vector<TreeNode*> trees; for (int r = from; r<=to; r++) { vector<TreeNode*>& lsub = dp[id(from, r-1)]; vector<TreeNode*>& rsub = dp[id(r+1, to)]; for (TreeNode* lsubroot : lsub) { for (TreeNode* rsubroot: rsub) { TreeNode* root = new TreeNode(r); root->left = lsubroot; root->right= rsubroot; trees.push_back(root); } } } dp.insert(make_pair(id(from, to), trees)); } } return dp[id(1, n)]; } long id(long from, long to) { return from > to ? 0 : (from<<32)|to; } };