Skip to content

Commit adb3b2d

Browse files
authored
added solution and test cases for 1145 (fishercoder1534#153)
1 parent db7b16b commit adb3b2d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.fishercoder.solutions;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
public class _1145 {
5+
public static class Solution1 {
6+
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
7+
if (root == null) {
8+
return false;
9+
}
10+
11+
if (root.val == x) {
12+
// 3 possible paths to block, left, right, parent
13+
int leftCount = countNodes(root.left);
14+
int rightCount = countNodes(root.right);
15+
int parent = n - (leftCount + rightCount + 1);
16+
17+
// possible to win if no. of nodes in 1 path is > than sum of nodes in the other 2 paths
18+
return parent > (leftCount + rightCount) || leftCount > (parent + rightCount) || rightCount > (parent + leftCount);
19+
}
20+
return btreeGameWinningMove(root.left, n, x) || btreeGameWinningMove(root.right, n, x);
21+
}
22+
23+
private int countNodes(TreeNode root) {
24+
if (root == null) {
25+
return 0;
26+
}
27+
return countNodes(root.left) + countNodes(root.right) + 1;
28+
}
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
import com.fishercoder.common.utils.TreeUtils;
5+
import com.fishercoder.solutions._1145;
6+
import org.junit.Assert;
7+
import org.junit.BeforeClass;
8+
import org.junit.Test;
9+
10+
import java.util.Arrays;
11+
12+
import static junit.framework.Assert.assertEquals;
13+
14+
public class _1145Test {
15+
16+
private static _1145.Solution1 solution1;
17+
private static TreeNode root1;
18+
private static int n;
19+
private static int x;
20+
21+
@BeforeClass
22+
public static void setup() {
23+
solution1 = new _1145.Solution1();
24+
}
25+
26+
@Test
27+
public void test1() {
28+
root1 = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
29+
n = 11;
30+
x = 3;
31+
Assert.assertEquals(true, solution1.btreeGameWinningMove(root1, n, x));
32+
}
33+
}

0 commit comments

Comments
 (0)