Skip to content

Create 2096. Step-By-Step Directions From a Binary Tree Node to Another #531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions 2096. Step-By-Step Directions From a Binary Tree Node to Another
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:

void f(TreeNode *root,bool &get,string &str,int st){
if(get){
str.pop_back();
return;
}
if(!root){
str.pop_back();
return;
}
if(root->val == st){
get = true;
return;
}
str+='L';
f(root->left,get,str,st);
if(get) return;
str+='R';
f(root->right,get,str,st);
if(get) return;
str+='U';
str.pop_back();
str.pop_back();
}
string getDirections(TreeNode* root, int startValue, int destValue) {
bool get = false;
string ststr = "",endstr="",ans="";
f(root,get,ststr,startValue);
get = false;
f(root,get,endstr,destValue);
if(ststr==""){
return endstr;
}
if(endstr==""){
for(int i=0;i<ststr.size();i++){
if(ststr[i]=='L' || ststr[i]=='R'){
ststr[i]='U';
}
}
return ststr;
}
if(ststr[0]==endstr[0]){
string st,end;
int i=1;
while(i<min(ststr.size(),endstr.size())){
if(ststr[i]==endstr[i]){
i++;
}
else{
break;
}
}
if(i<min(ststr.size(),endstr.size())){
int j = i,k=i;
while(i<ststr.size()){
ststr[i]='U';
i++;
}
return ststr.substr(k,ststr.size()) + endstr.substr(j,endstr.size());
}
else{
if(i==ststr.size()){
return endstr.substr(i,endstr.size());
}
else{
int j = i;
while(i<ststr.size()){
ststr[i] = 'U';
i++;
}
return ststr.substr(j,ststr.size());
}
}
}
string temp;
for(int i=0;i<ststr.size();i++){
temp+='U';
}
temp+=endstr;
return temp;
}
};
Loading