Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3d94752

Browse files
authored
Create Step-By-Step Directions From a Binary Tree Node to Another.java
1 parent b9ae48f commit 3d94752

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)