-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
53 lines (51 loc) · 1.52 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
/**
* 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:
string getDirections(TreeNode* root, int startValue, int destValue) {
TreeNode* node = lca(root, startValue, destValue);
string pathToStart, pathToDest;
dfs(node, startValue, pathToStart);
dfs(node, destValue, pathToDest);
return string(pathToStart.size(), 'U') + pathToDest;
}
private:
TreeNode* lca(TreeNode* node, int p, int q) {
if (node == nullptr || node->val == p || node->val == q) {
return node;
}
TreeNode* left = lca(node->left, p, q);
TreeNode* right = lca(node->right, p, q);
if (left != nullptr && right != nullptr) {
return node;
}
return left != nullptr ? left : right;
}
bool dfs(TreeNode* node, int x, string& path) {
if (node == nullptr) {
return false;
}
if (node->val == x) {
return true;
}
path.push_back('L');
if (dfs(node->left, x, path)) {
return true;
}
path.back() = 'R';
if (dfs(node->right, x, path)) {
return true;
}
path.pop_back();
return false;
}
};