I was solving LeetCode problem 2096. Step-By-Step Directions From a Binary Tree Node to Another:
You are given the
rootof a binary tree withnnodes. Each node is uniquely assigned a value from1ton. You are also given an integerstartValuerepresenting the value of the start nodes, and a different integerdestValuerepresenting the value of the destination nodet.Find the shortest path starting from node
sand ending at nodet. Generate step-by-step directions of such path as a string consisting of only the uppercase letters'L','R', and'U'. Each letter indicates a specific direction:
'L'means to go from a node to its left child node.'R'means to go from a node to its right child node.'U'means to go from a node to its parent node.Return the step-by-step directions of the shortest path from node
sto nodet.
This is the code I submitted:
class Solution {
public:
map<TreeNode*,TreeNode*>parent;
TreeNode* start = NULL;
string global ="";
void trav(TreeNode* root , int startValue )
{
if(root==NULL)
{
return ;
}
if(root->val==startValue )
{
start = root;
}
if(root->left)
{
parent[root->left] = root ;
trav( root->left, startValue);
}
if(root->right)
{
parent[root->right] = root ;
trav( root->right, startValue);
}
}
void direct(TreeNode* root, int destValue, TreeNode *prev , string path )
{
if(root==NULL )
{
return;
}
if(root->val == destValue)
{
global += path;
return ;
}
if(root->left!=prev)
{
direct(root->left,destValue, root,path+"L");
}
if(root->right!=prev)
{
direct(root->right,destValue, root,path+"R");
}
direct(parent[root],destValue,root, path+"U");
}
string getDirections(TreeNode* root, int startValue, int destValue)
{
parent[root]= NULL;
trav(root, startValue);
direct(start,destValue, NULL,"");
parent.clear();
return global ;
}
};
When I ran it on a compiler (Link) it ran with no error. But submitting the code on the platform (Submission Link ) gives a memory limit error.
I know I have created a map globally, but that should not be the cause of this error as the error occurs even when running a single test case.
I am stuck on this issue. What am I doing wrong?