Leetcode 95. 不同的二叉搜尋樹 II
阿新 • • 發佈:2018-12-24
似乎寫複雜了,列舉所有的結果
/**
* 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:
struct node {
int l, r;
};
vector<int> sta;
vector <TreeNode*> q, ans;
vector<node> p;
void inorderTraversal(TreeNode* &root) {
vector<TreeNode*> sta;
int num = 1;
sta.push_back(root);
while (sta.back()->left) sta.push_back(sta.back()->left);
while (!sta.empty()) {
TreeNode* p = sta.back(); sta.pop_back();
p->val = num++;
if (p->right) {
sta.push_back(p->right);
while (sta.back()->left) sta.push_back(sta.back()->left);
}
}
}
void dfs(int next, int &n, int &ptr) {
if (next > n) {
ptr = 0;
for (auto &x : sta) p[x].r = 0 ;
for (int i = 0; i < n; ++i)
q[i] = new TreeNode(0);
for (int i = 0; i < n; ++i)
q[i]->left = p[i + 1].l ? q[p[i + 1].l - 1] : NULL, q[i]->right = p[i + 1].r ? q[p[i + 1].r - 1] : NULL;
inorderTraversal(q[0]);
ans.push_back(q[0]);
return;
}
if (sta.empty()) {
ptr = next;
sta.push_back(next);
dfs(next + 1, n, p[next].l);
sta.pop_back();
}
else {
ptr = next;
sta.push_back(next);
dfs(next + 1, n, p[next].l);
sta.pop_back();
ptr = 0;
int k = sta.back();
sta.pop_back();
dfs(next, n, p[k].r);
sta.push_back(k);
}
}
vector<TreeNode*> generateTrees(int n) {
if (!n) return ans;
p.resize(n + 1), q.resize(n);
sta.push_back(1), dfs(2, n, p[1].l);
return ans;
}
};