-
Notifications
You must be signed in to change notification settings - Fork 1
/
StepByStepDirectionsFromABinaryTreeNodeToAnother.java
68 lines (58 loc) · 2.13 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/
public class StepByStepDirectionsFromABinaryTreeNodeToAnother {
private final TreeNode root;
private final int startValue;
private final int destValue;
private final List<String> paths = new ArrayList<>();
public StepByStepDirectionsFromABinaryTreeNodeToAnother(
TreeNode root,
int startValue,
int destValue
) {
this.root = root;
this.startValue = startValue;
this.destValue = destValue;
}
public String solution() {
TreeNode lca = lca(root, startValue, destValue);
pathFor(lca, startValue, new StringBuilder());
pathFor(lca, destValue, new StringBuilder());
StringBuilder result = new StringBuilder();
result.append("U".repeat(paths.get(0).length()));
result.append(paths.get(1));
return result.toString();
}
private TreeNode lca(TreeNode node, int startValue, int destValue) {
if (node != null) {
if (node.val == startValue || node.val == destValue) {
return node;
}
TreeNode left = lca(node.left, startValue, destValue);
TreeNode right = lca(node.right, startValue, destValue);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
return null;
}
private void pathFor(TreeNode node, int val, StringBuilder path) {
if (node != null) {
if (node.val == val) {
paths.add(path.toString());
} else {
if (node.left != null) {
pathFor(node.left, val, path.append('L'));
}
if (node.right != null) {
pathFor(node.right, val, path.append('R'));
}
path.deleteCharAt(path.length() - 1);
}
}
}
}