-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
65 lines (56 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
56
57
58
59
60
61
62
63
64
65
#include <string>
using namespace std;
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 {
private:
bool dfs(TreeNode* current, int target, string& directions) {
if (current == nullptr) {
return false;
}
if (current->val == target) {
return true;
}
directions += "L";
bool isFound = dfs(current->left, target, directions);
if (isFound) {
return true;
}
directions.pop_back();
directions += "R";
isFound = dfs(current->right, target, directions);
if (isFound) {
return true;
}
directions.pop_back();
return false;
}
public:
// From their Lowest Common Ancestor:
// shortest path from start to dest = shortest path to start + shortest path
// to dest.
//
// Not a Binary Search Tree => DFS/BFS to find both.
string getDirections(TreeNode* root, int startValue, int destValue) {
string directionToStart;
dfs(root, startValue, directionToStart);
string directionToDest;
dfs(root, destValue, directionToDest);
// Find LowestCommonAncestor by matching prefix.
int lca = 0;
while (directionToStart[lca] == directionToDest[lca]) {
++lca;
}
string directions =
string(directionToStart.length() - lca, 'U') +
directionToDest.substr(lca, directionToDest.length() - lca);
return directions;
}
};