class Solution {
public:
string getDirections(TreeNode* root, int startValue, int destValue)
{
string startPath, destPath;
findPath(root, startValue, startPath);
findPath(root, destValue, destPath);
string directions;
int commonPath = 0;
while (commonPath < startPath.size() && commonPath < destPath.size() && startPath[commonPath] == destPath[commonPath])
{
commonPath++;
}
for (int i = commonPath; i < startPath.size(); ++i)
{
directions += "U";
}
for (int i = commonPath; i < destPath.size(); ++i)
{
directions += destPath[i];
}
return directions;
}
bool findPath(TreeNode* root, int target, string& path)
{
if (!root) return false;
if (root->val == target) return true;
path += 'L';
if (findPath(root->left, target, path)) return true;
path.pop_back();
path += 'R';
if (findPath(root->right, target, path)) return true;
path.pop_back();
return false;
}
};