Skip to content

Commit 608e9a2

Browse files
authored
Create K-th Symbol in Grammar.java
1 parent 12b5aa0 commit 608e9a2

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Medium/K-th Symbol in Grammar.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int kthGrammar(int n, int k) {
3+
return depthFirstSearch(n, k, 0);
4+
}
5+
6+
private int depthFirstSearch(int n, int k, int root) {
7+
if (n == 1) {
8+
return root;
9+
}
10+
int nodeCount = (int) Math.pow(2, n - 1);
11+
if (k > (nodeCount / 2)) {
12+
int nextRoot = (root == 0) ? 1 : 0;
13+
return depthFirstSearch(n - 1, k - (nodeCount / 2), nextRoot);
14+
}
15+
int nextRoot = (root == 0) ? 0 : 1;
16+
return depthFirstSearch(n - 1, k, nextRoot);
17+
}
18+
}

0 commit comments

Comments
 (0)