-
Notifications
You must be signed in to change notification settings - Fork 5
/
StepByStepDirectionsFromABinaryTreeNodeToAnother.java
50 lines (47 loc) · 1.64 KB
/
StepByStepDirectionsFromABinaryTreeNodeToAnother.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int start, end;
StringBuilder build1, build2;
public String getDirections(TreeNode root, int startValue, int destValue) {
build1 = new StringBuilder("");
build2 = new StringBuilder("");
this.start = startValue;
this.end = destValue;
recur(root,new StringBuilder(""));
int i = 0;
while (i < build1.length() && i < build2.length() && build1.charAt(i) == build2.charAt(i))
++i;
StringBuilder result = new StringBuilder("");
for (int move = i; move < build1.length(); ++move)
result.append("U");
for (int move = i; move < build2.length(); ++move)
result.append(build2.charAt(move));
return result.toString();
}
private void recur(TreeNode root, StringBuilder build)
{
if (root == null) return;
if (root.val == start) build1 = new StringBuilder(build);
else if (root.val == end) build2 = new StringBuilder(build);
build.append("L");
recur(root.left,build);
build.replace(build.length()-1,build.length(),"R");
recur(root.right,build);
build.delete(build.length()-1,build.length());
}
}