Skip to content

Commit 3f107b2

Browse files
committed
Create Solution2.java
1 parent 5378a7d commit 3f107b2

File tree

1 file changed

+63
-0
lines changed
  • solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
static byte[] path = new byte[200_001];
18+
int strtLevel = -1;
19+
int destLevel = -1;
20+
int comnLevel = -1;
21+
22+
public String getDirections(TreeNode root, int startValue, int destValue) {
23+
findPaths(root, startValue, destValue, 100_000);
24+
int answerIdx = comnLevel;
25+
for (int i = strtLevel; i > comnLevel; i--) {
26+
path[--answerIdx] = 'U';
27+
}
28+
return new String(path, answerIdx, destLevel - answerIdx);
29+
}
30+
31+
private int findPaths(TreeNode node, int strtVal, int destVal, int level) {
32+
if (node == null) {
33+
return 0;
34+
}
35+
int result = 0;
36+
if (node.val == strtVal) {
37+
strtLevel = level;
38+
result = 1;
39+
} else if (node.val == destVal) {
40+
destLevel = level;
41+
result = 1;
42+
}
43+
int leftFound = 0;
44+
int rightFound = 0;
45+
if (comnLevel < 0) {
46+
if (destLevel < 0) {
47+
path[level] = 'L';
48+
}
49+
leftFound = findPaths(node.left, strtVal, destVal, level + 1);
50+
rightFound = 0;
51+
if (comnLevel < 0) {
52+
if (destLevel < 0) {
53+
path[level] = 'R';
54+
}
55+
rightFound = findPaths(node.right, strtVal, destVal, level + 1);
56+
}
57+
}
58+
if (comnLevel < 0 && leftFound + rightFound + result == 2) {
59+
comnLevel = level;
60+
}
61+
return result | leftFound | rightFound;
62+
}
63+
}

0 commit comments

Comments
 (0)