-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_04.09_BSTSequences.cc
60 lines (56 loc) · 1.28 KB
/
Problem_04.09_BSTSequences.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <algorithm>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
void dfs(vector<TreeNode*>& nodes, vector<vector<int>>& ans, vector<int>& path)
{
if (nodes.size() == 0)
{
ans.push_back(path);
return;
}
// 相同层的节点都可以不同顺序
for (int i = 0; i < nodes.size(); i++)
{
TreeNode* node = nodes[i];
path.push_back(node->val);
nodes.erase(nodes.begin() + i);
if (node->left != NULL)
{
nodes.push_back(node->left);
}
if (node->right != NULL)
{
nodes.push_back(node->right);
}
dfs(nodes, ans, path);
// 回溯
nodes.insert(nodes.begin() + i, node);
nodes.erase(std::remove(nodes.begin(), nodes.end(), node->left), nodes.end());
nodes.erase(std::remove(nodes.begin(), nodes.end(), node->right), nodes.end());
path.pop_back();
}
}
vector<vector<int>> BSTSequences(TreeNode* root)
{
if (root == NULL)
{
return {{}};
}
vector<vector<int>> ans;
vector<int> path;
vector<TreeNode*> nodes;
nodes.push_back(root);
dfs(nodes, ans, path);
return ans;
}
};