-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2096.StepByStepDirectionsFromABinaryTreeNodeToAnother.cpp
More file actions
67 lines (58 loc) · 1.69 KB
/
2096.StepByStepDirectionsFromABinaryTreeNodeToAnother.cpp
File metadata and controls
67 lines (58 loc) · 1.69 KB
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
66
67
/**
* 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 m_activePath = "", m_startPath = "Not found.", m_destPath = "Not found.";
int m_startValue, m_destValue;
void findTargetNodes(TreeNode* root) {
// Check if start.
if (root->val == m_startValue)
m_startPath = m_activePath;
// Check if destination.
else if (root->val == m_destValue)
m_destPath = m_activePath;
// Path to left node.
if (root->left != nullptr) {
m_activePath.push_back('L');
findTargetNodes(root->left);
m_activePath.pop_back();
}
// Path to right node.
if (root->right != nullptr) {
m_activePath.push_back('R');
findTargetNodes(root->right);
m_activePath.pop_back();
}
}
string getDirections(TreeNode* root, int startValue, int destValue) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Setup variables.
m_startValue = startValue;
m_destValue = destValue;
// Process nodes.
findTargetNodes(root);
// Find common depth.
int commonDepth = 0;
while (m_startPath[commonDepth] == m_destPath[commonDepth]) commonDepth++;
// Generate path.
string startToDestPath = "";
const int startDepth = m_startPath.size();
for (int i = commonDepth; i < startDepth; i++)
startToDestPath.push_back('U');
startToDestPath += m_destPath.substr(commonDepth);
// Return path.
return startToDestPath;
}
};