diff --git a/src/main/java/com/fishercoder/solutions/_965.java b/src/main/java/com/fishercoder/solutions/_965.java index 09b1c5b9d3..e8ddf0c291 100644 --- a/src/main/java/com/fishercoder/solutions/_965.java +++ b/src/main/java/com/fishercoder/solutions/_965.java @@ -21,4 +21,11 @@ private boolean dfs(TreeNode root, int value) { return dfs(root.left, value) && dfs(root.right, value); } } + public static class Solution2 { + public boolean isUnivalTree(TreeNode root) { + boolean leftUnivaled = root.left == null || root.left.val == root.val && isUnivalTree(root.left); + boolean rightUnivaled = root.right == null || root.right.val == root.val && isUnivalTree(root.right); + return leftUnivaled && rightUnivaled; + } + } } diff --git a/src/test/java/com/fishercoder/_965Test.java b/src/test/java/com/fishercoder/_965Test.java index 50b355d150..6de473243f 100644 --- a/src/test/java/com/fishercoder/_965Test.java +++ b/src/test/java/com/fishercoder/_965Test.java @@ -2,22 +2,24 @@ import com.fishercoder.common.classes.TreeNode; import com.fishercoder.common.utils.TreeUtils; -import com.fishercoder.solutions._14; import com.fishercoder.solutions._965; -import java.util.Arrays; -import java.util.List; import org.junit.BeforeClass; import org.junit.Test; +import java.util.Arrays; + import static org.junit.Assert.assertEquals; public class _965Test { private static _965.Solution1 solution1; + private static _965.Solution2 solution2; private static TreeNode root; @BeforeClass public static void setup() { + solution1 = new _965.Solution1(); + solution2 = new _965.Solution2(); } @Test @@ -31,4 +33,14 @@ public void test2() { root = TreeUtils.constructBinaryTree(Arrays.asList(2, 2, 2, 5, 2)); assertEquals(false, solution1.isUnivalTree(root)); } + @Test + public void test3() { + root = TreeUtils.constructBinaryTree(Arrays.asList(-1, -1, -1, -1, -1, -1, -1)); + assertEquals(true, solution2.isUnivalTree(root)); + } + @Test + public void test4() { + root = TreeUtils.constructBinaryTree(Arrays.asList(2, 2, 2, 2, 2, 2, 1)); + assertEquals(false, solution2.isUnivalTree(root)); + } }