-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
55 lines (52 loc) · 1.57 KB
/
Solution.cpp
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
/**
* 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:
unordered_map<int, vector<pair<int, char>>> edges;
unordered_set<int> visited;
string ans;
string getDirections(TreeNode* root, int startValue, int destValue) {
ans = "";
traverse(root);
string t = "";
dfs(startValue, destValue, t);
return ans;
}
void traverse(TreeNode* root) {
if (!root) return;
if (root->left) {
edges[root->val].push_back({root->left->val, 'L'});
edges[root->left->val].push_back({root->val, 'U'});
}
if (root->right) {
edges[root->val].push_back({root->right->val, 'R'});
edges[root->right->val].push_back({root->val, 'U'});
}
traverse(root->left);
traverse(root->right);
}
void dfs(int start, int dest, string& t) {
if (visited.count(start)) return;
if (start == dest) {
if (ans == "" || ans.size() > t.size()) ans = t;
return;
}
visited.insert(start);
if (edges.count(start)) {
for (auto& item : edges[start]) {
t += item.second;
dfs(item.first, dest, t);
t.pop_back();
}
}
}
};