Step by step Shortest Path from source node to destination node in a Binary Tree
Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below.
- Going from one node to its left child node is indicated by the letter ‘L’.
- Going from one node to its right child node is indicated by the letter ‘R’.
- To navigate from a node to its parent node, use the letter ‘U’.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: root = [5, 1, 2, 3, null, 6, 4], startValue = 3, destValue = 6
5
/ \
1 2
/ / \
3 6 4Output: “UURL”
Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6.Input: root = [2, 1], startValue = 2, destValue = 1
2
/
1Output: “L”
Explanation: The shortest path is: 2 → 1.
Approach: The simplest way to solve this problem is to use the LCA (Lowest Common Ancestor) of a binary tree. Follow the steps below to solve the given problem.
- Apply LCA to get a new root.
- Get the Path from the new root to start and dest.
- Concatenate startPath and destPath, and make sure to replace startPath’s char with ‘U’.
Below is the implementation of the above approach.
C++
// C++ program for above approach#include <iostream>using namespace std; // Structure of Treeclass TreeNode {public: int val; TreeNode* left; TreeNode* right; TreeNode(int val2) { val = val2; left = NULL; right = NULL; }}; // Function to find LCA of two nodesTreeNode* lca(TreeNode* root, int startValue, int destValue){ // Base Case if (!root) return NULL; if (root->val == startValue) return root; if (root->val == destValue) return root; auto l = lca(root->left, startValue, destValue); auto r = lca(root->right, startValue, destValue); if (l && r) return root; return l ? l : r;}bool getPath(TreeNode* root, int value, string& path){ // Base Cases if (!root) return false; if (root->val == value) return true; path += 'L'; auto res = getPath(root->left, value, path); if (res) return true; path.pop_back(); path += 'R'; res = getPath(root->right, value, path); if (res) return true; path.pop_back(); return false;} // Function to get directionsstring getDirections(TreeNode* root, int startValue, int destValue){ // Find the LCA first root = lca(root, startValue, destValue); string p1, p2; // Get the path getPath(root, startValue, p1); getPath(root, destValue, p2); for (auto& c : p1) c = 'U'; // Return the concatenation return p1 + p2;} // Driver Codeint main(){ /* 5 / \ 1 2 / / \ 3 6 4 */ TreeNode* root = new TreeNode(5); root->left = new TreeNode(1); root->right = new TreeNode(2); root->left->left = new TreeNode(3); root->right->left = new TreeNode(6); root->right->right = new TreeNode(4); int startValue = 3; int endValue = 6; // Function Call string ans = getDirections( root, startValue, endValue); // Print answer cout << ans;} |
UURL
Time complexity: O(3N), Because three traversals are done.
Auxiliary Space: O(1)
Efficient Approach: This approach is implementation based but LCA is not used in this approach. Follow the steps below to solve the given problem.
- Build directions for both start and destination from the root.
- Say we get “LLRRL” and “LRR”.
- Remove common prefix path.
- We remove “L”, and now start direction is “LRRL”, and destination – “RR”
- Replace all steps in the start direction to “U” and add the destination direction.
- The result is “UUUU” + “RR”.
Below is the implementation of the above approach.
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Structure of Treeclass TreeNode {public: int val; TreeNode* left; TreeNode* right; TreeNode(int val2) { val = val2; left = NULL; right = NULL; }}; // Find Functionbool find(TreeNode* n, int val, string& path){ if (n->val == val) return true; if (n->left && find(n->left, val, path)) { path.push_back('L'); return true; } if (n->right && find(n->right, val, path)) { path.push_back('R'); return true; } return false;} // Function to keep track // of directions at any pointstring getDirections(TreeNode* root, int startValue, int destValue){ // To store the startPath and destPath string s_p, d_p; find(root, startValue, s_p); find(root, destValue, d_p); while (!s_p.empty() && !d_p.empty() && s_p.back() == d_p.back()) { s_p.pop_back(); d_p.pop_back(); } for (int i = 0; i < s_p.size(); i++) { s_p[i] = 'U'; } reverse(d_p.begin(), d_p.end()); string ans = s_p + d_p; return ans;} // Driver Codeint main(){ /* 5 / \ 1 2 / / \ 3 6 4 */ TreeNode* root = new TreeNode(5); root->left = new TreeNode(1); root->right = new TreeNode(2); root->left->left = new TreeNode(3); root->right->left = new TreeNode(6); root->right->right = new TreeNode(4); int startValue = 3; int endValue = 6; // Function Call string ans = getDirections( root, startValue, endValue); // Print the result cout << ans;} |
UURL
Time complexity: O(N)
Auxiliary Space: O(1), If recursion stack space if neglected.


