Leet Code Daily 2024-07-16 - Step-By-Step Directions From a Binary Tree Node to Another
Code
● ● ●c++/**
* 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:
void dfs(TreeNode* root, unordered_map<int, TreeNode*>& val_to_ptr,
unordered_map<TreeNode*, TreeNode*>& parent) {
if (root != nullptr) {
val_to_ptr[root->val] = root;
if (root->left != nullptr) {
parent[root->left] = root;
dfs(root->left, val_to_ptr, parent);
}
if (root->right != nullptr) {
parent[root->right] = root;
dfs(root->right, val_to_ptr, parent);
}
}
}
string getDirections(TreeNode* root, int startValue, int destValue) {
unordered_map<int, TreeNode*> val_to_ptr;
unordered_map<TreeNode*, TreeNode*> parent;
dfs(root, val_to_ptr, parent);
unordered_set<TreeNode*> dest_tree_path;
for (auto ptr = val_to_ptr[destValue]; ptr != nullptr;
ptr = parent[ptr]) {
dest_tree_path.insert(ptr);
}
string ret = "";
for (auto ptr = val_to_ptr[startValue]; ptr != val_to_ptr[destValue];) {
if (ptr->left != nullptr && dest_tree_path.contains(ptr->left)) {
ret.push_back('L');
ptr = ptr->left;
continue;
}
if (ptr->right != nullptr && dest_tree_path.contains(ptr->right)) {
ret.push_back('R');
ptr = ptr->right;
continue;
}
ptr = parent[ptr];
ret.push_back('U');
}
return ret;
}
};