2096.cpp (688B)
1 class Solution { 2 bool find(TreeNode *n, int val, string &path) const { 3 if (n->val == val) return true; 4 5 if (n->left && find(n->left, val, path)) 6 path.push_back('L'); 7 else if (n->right && find(n->right, val, path)) 8 path.push_back('R'); 9 10 return !path.empty(); 11 } 12 13 public: 14 string getDirections(TreeNode *root, int startValue, int destValue) const { 15 string s, d; 16 17 find(root, startValue, s); 18 find(root, destValue, d); 19 20 while (!s.empty() && !d.empty() && s.back() == d.back()) 21 s.pop_back(), d.pop_back(); 22 return string(s.size(), 'U') + string(rbegin(d), rend(d)); 23 } 24 };