Approach
Depth-first search
For Step-By-Step Directions From a Binary Tree Node to Another, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 30 lines of Java from the credited upstream file 2096-2.java.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String getDirections(TreeNode root, int startValue, int destValue) {3 StringBuilder pathToStart = new StringBuilder();4 StringBuilder pathToDest = new StringBuilder();5 6 dfs(root, startValue, pathToStart);7 dfs(root, destValue, pathToDest);8 9 while (pathToStart.length() > 0 && pathToDest.length() > 0 &&10 pathToStart.charAt(pathToStart.length() - 1) ==11 pathToDest.charAt(pathToDest.length() - 1)) {12 pathToStart.setLength(pathToStart.length() - 1);13 pathToDest.setLength(pathToDest.length() - 1);14 }15 16 return "U".repeat(pathToStart.length()) + pathToDest.reverse().toString();17 }18 19 20 private boolean dfs(TreeNode root, int val, StringBuilder sb) {21 if (root.val == val)22 return true;23 if (root.left != null && dfs(root.left, val, sb))24 sb.append("L");25 else if (root.right != null && dfs(root.right, val, sb))26 sb.append("R");27 return sb.length() > 0;28 }29}30