|
| 1 | +package com.fishercoder.solutions.thirdthousand; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +public class _2096 { |
| 6 | + public static class Solution1 { |
| 7 | + /** |
| 8 | + * Steps for this problem: |
| 9 | + * 1. find the path from root the start and dest respectively, mark them using two directions: 'L' and 'R', i.e. you can only go down from root, so there's no up, 'U' direction; |
| 10 | + * 2. the LCA (the lowest common ancestor) of start and dest will be the joint of the shortest path; |
| 11 | + * 3. find the longest common prefix of these two paths, that can be cut off; |
| 12 | + * 4. reverse the startPath, so it becomes the path from start to LCA, then concatenate with destPath |
| 13 | + */ |
| 14 | + public String getDirections(TreeNode root, int startValue, int destValue) { |
| 15 | + StringBuilder sb = new StringBuilder(); |
| 16 | + String pathForStart = ""; |
| 17 | + if (findPathFromRoot(root, startValue, sb)) { |
| 18 | + pathForStart = sb.toString(); |
| 19 | + } |
| 20 | + sb.setLength(0); |
| 21 | + String pathForDest = ""; |
| 22 | + if (findPathFromRoot(root, destValue, sb)) { |
| 23 | + pathForDest = sb.toString(); |
| 24 | + } |
| 25 | + int lastIdenticalCharIndex = -1; |
| 26 | + int minLen = Math.min(pathForStart.length(), pathForDest.length()); |
| 27 | + for (int i = 0; i < minLen; i++) { |
| 28 | + if (pathForStart.charAt(i) == pathForDest.charAt(i)) { |
| 29 | + lastIdenticalCharIndex = i; |
| 30 | + } else { |
| 31 | + break; |
| 32 | + } |
| 33 | + } |
| 34 | + sb.setLength(0); |
| 35 | + sb.append(pathForStart.substring(lastIdenticalCharIndex + 1)); |
| 36 | + for (int i = 0; i < sb.length(); i++) { |
| 37 | + if (sb.charAt(i) == 'L' || sb.charAt(i) == 'R') { |
| 38 | + sb.setCharAt(i, 'U'); |
| 39 | + } |
| 40 | + } |
| 41 | + sb.append(pathForDest.substring(lastIdenticalCharIndex + 1)); |
| 42 | + return sb.toString(); |
| 43 | + } |
| 44 | + |
| 45 | + private boolean findPathFromRoot(TreeNode root, int target, StringBuilder sb) { |
| 46 | + if (root == null) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + if (root.val == target) { |
| 50 | + return true; |
| 51 | + } |
| 52 | + if (findPathFromRoot(root.left, target, sb.append("L"))) { |
| 53 | + return true; |
| 54 | + } |
| 55 | + sb.setLength(sb.length() - 1); |
| 56 | + if (findPathFromRoot(root.right, target, sb.append("R"))) { |
| 57 | + return true; |
| 58 | + } |
| 59 | + sb.setLength(sb.length() - 1); |
| 60 | + return false; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments