leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
2096.cpp (688B)
0 class Solution { 1 bool find(TreeNode *n, int val, string &path) const { 2 if (n->val == val) return true; 3 4 if (n->left && find(n->left, val, path)) 5 path.push_back('L'); 6 else if (n->right && find(n->right, val, path)) 7 path.push_back('R'); 8 9 return !path.empty(); 10 } 11 12 public: 13 string getDirections(TreeNode *root, int startValue, int destValue) const { 14 string s, d; 15 16 find(root, startValue, s); 17 find(root, destValue, d); 18 19 while (!s.empty() && !d.empty() && s.back() == d.back()) 20 s.pop_back(), d.pop_back(); 21 return string(s.size(), 'U') + string(rbegin(d), rend(d)); 22 } 23 };