1111 */
1212class Solution {
1313public:
14- unordered_map<int , vector<pair<int , char >>> edges;
15- unordered_set<int > visited;
16- string ans;
17-
1814 string getDirections (TreeNode* root, int startValue, int destValue) {
19- ans = " " ;
20- traverse (root) ;
21- string t = " " ;
22- dfs (startValue , destValue, t );
23- return ans ;
15+ TreeNode* node = lca (root, startValue, destValue) ;
16+ string pathToStart, pathToDest ;
17+ dfs (node, startValue, pathToStart) ;
18+ dfs (node , destValue, pathToDest );
19+ return string (pathToStart. size (), ' U ' ) + pathToDest ;
2420 }
2521
26- void traverse (TreeNode* root) {
27- if (!root) return ;
28- if (root->left ) {
29- edges[root->val ].push_back ({root->left ->val , ' L' });
30- edges[root->left ->val ].push_back ({root->val , ' U' });
22+ private:
23+ TreeNode* lca (TreeNode* node, int p, int q) {
24+ if (node == nullptr || node->val == p || node->val == q) {
25+ return node;
3126 }
32- if (root->right ) {
33- edges[root->val ].push_back ({root->right ->val , ' R' });
34- edges[root->right ->val ].push_back ({root->val , ' U' });
27+ TreeNode* left = lca (node->left , p, q);
28+ TreeNode* right = lca (node->right , p, q);
29+ if (left != nullptr && right != nullptr ) {
30+ return node;
3531 }
36- traverse (root->left );
37- traverse (root->right );
32+ return left != nullptr ? left : right;
3833 }
3934
40- void dfs (int start, int dest, string& t) {
41- if (visited.count (start)) return ;
42- if (start == dest) {
43- if (ans == " " || ans.size () > t.size ()) ans = t;
44- return ;
35+ bool dfs (TreeNode* node, int x, string& path) {
36+ if (node == nullptr ) {
37+ return false ;
38+ }
39+ if (node->val == x) {
40+ return true ;
41+ }
42+ path.push_back (' L' );
43+ if (dfs (node->left , x, path)) {
44+ return true ;
4545 }
46- visited.insert (start);
47- if (edges.count (start)) {
48- for (auto & item : edges[start]) {
49- t += item.second ;
50- dfs (item.first , dest, t);
51- t.pop_back ();
52- }
46+ path.back () = ' R' ;
47+ if (dfs (node->right , x, path)) {
48+ return true ;
5349 }
50+ path.pop_back ();
51+ return false ;
5452 }
55- };
53+ };
0 commit comments