Spark應用程式-任務的排程
阿新 • • 發佈:2021-01-10
Given an integern
, generate all structurally uniqueBST's(binary search trees) that store values 1 ...n.
Example:
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
Constraints:
0 <= n <= 8
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * };*/ class Solution { public: //遞迴 vector<TreeNode*> generate(int start,int end){ vector<TreeNode*> res; if(start > end) { res.push_back(NULL); return res; } if(start == end){ TreeNode* node = new TreeNode(start); res.push_back(node);return res; } for(int i=start;i<=end;i++){ vector<TreeNode*> left = generate(start,i-1); vector<TreeNode*> right = generate(i+1,end); for(auto l:left){ for(auto r:right){ TreeNode* root = new TreeNode(i); root->left = l; root->right= r; res.push_back(root); } } } return res; } vector<TreeNode*> generateTrees(int n) { if(n == 0) return vector<TreeNode*>{}; return generate(1,n); } };