|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * public class TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode left; |
| 6 | + * TreeNode right; |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
| 14 | + * } |
| 15 | + */ |
| 16 | +class Solution { |
| 17 | + public String getDirections(TreeNode root, int startValue, int destValue) { |
| 18 | + StringBuilder sourcePath = new StringBuilder(); |
| 19 | + StringBuilder destinationPath = new StringBuilder(); |
| 20 | + findPath(root, startValue, sourcePath); |
| 21 | + findPath(root, destValue, destinationPath); |
| 22 | + int idx = 0; |
| 23 | + // Remove common prefix |
| 24 | + while (idx < Math.min(sourcePath.length(), destinationPath.length()) && |
| 25 | + sourcePath.charAt(sourcePath.length() - idx - 1) == destinationPath.charAt(destinationPath.length() - idx - 1)) { |
| 26 | + idx++; |
| 27 | + } |
| 28 | + // Replace remaining sourcePath with 'U' and append remaining destinationPath |
| 29 | + return "U".repeat(sourcePath.length() - idx) + destinationPath.reverse().toString().substring(idx); |
| 30 | + } |
| 31 | + |
| 32 | + private boolean findPath(TreeNode root, int value, StringBuilder sb) { |
| 33 | + if (root.val == value) { |
| 34 | + return true; |
| 35 | + } |
| 36 | + if (root.left != null && findPath(root.left, value, sb)) { |
| 37 | + sb.append("L"); |
| 38 | + } |
| 39 | + else if (root.right != null && findPath(root.right, value, sb)) { |
| 40 | + sb.append("R"); |
| 41 | + } |
| 42 | + return sb.length() > 0; |
| 43 | + } |
| 44 | +} |
0 commit comments