-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
41 lines (39 loc) · 1.28 KB
/
Solution.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
class Solution {
public String getDirections(TreeNode root, int startValue, int destValue) {
TreeNode node = lca(root, startValue, destValue);
StringBuilder pathToStart = new StringBuilder();
StringBuilder pathToDest = new StringBuilder();
dfs(node, startValue, pathToStart);
dfs(node, destValue, pathToDest);
return "U".repeat(pathToStart.length()) + pathToDest.toString();
}
private TreeNode lca(TreeNode node, int p, int q) {
if (node == null || node.val == p || node.val == q) {
return node;
}
TreeNode left = lca(node.left, p, q);
TreeNode right = lca(node.right, p, q);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
private boolean dfs(TreeNode node, int x, StringBuilder path) {
if (node == null) {
return false;
}
if (node.val == x) {
return true;
}
path.append('L');
if (dfs(node.left, x, path)) {
return true;
}
path.setCharAt(path.length() - 1, 'R');
if (dfs(node.right, x, path)) {
return true;
}
path.deleteCharAt(path.length() - 1);
return false;
}
}