Skip to content

added solution and test cases for 1145 #153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/main/java/com/fishercoder/solutions/_1145.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.fishercoder.solutions;

import com.fishercoder.common.classes.TreeNode;
public class _1145 {
public static class Solution1 {
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
if (root == null) {
return false;
}

if (root.val == x) {
// 3 possible paths to block, left, right, parent
int leftCount = countNodes(root.left);
int rightCount = countNodes(root.right);
int parent = n - (leftCount + rightCount + 1);

// possible to win if no. of nodes in 1 path is > than sum of nodes in the other 2 paths
return parent > (leftCount + rightCount) || leftCount > (parent + rightCount) || rightCount > (parent + leftCount);
}
return btreeGameWinningMove(root.left, n, x) || btreeGameWinningMove(root.right, n, x);
}

private int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
}
33 changes: 33 additions & 0 deletions src/test/java/com/fishercoder/_1145Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.fishercoder;

import com.fishercoder.common.classes.TreeNode;
import com.fishercoder.common.utils.TreeUtils;
import com.fishercoder.solutions._1145;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Arrays;

import static junit.framework.Assert.assertEquals;

public class _1145Test {

private static _1145.Solution1 solution1;
private static TreeNode root1;
private static int n;
private static int x;

@BeforeClass
public static void setup() {
solution1 = new _1145.Solution1();
}

@Test
public void test1() {
root1 = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
n = 11;
x = 3;
Assert.assertEquals(true, solution1.btreeGameWinningMove(root1, n, x));
}
}