* BAEL-3400

* BALE-3400 | moved to algorithm-miscellaneous-5

* BAEL-3400 | added modifiers
This commit is contained in:
Macieg
2019-11-05 02:40:19 +01:00
committed by maibin
parent cdeb947e42
commit f2d9829b91
5 changed files with 162 additions and 0 deletions
@@ -0,0 +1,26 @@
package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
@Test
public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
for (Tree tree : balancedTrees()) {
assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree));
}
}
@Test
public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
for (Tree tree : unbalancedTrees()) {
assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree));
}
}
private String toString(Tree tree) {
return tree != null ? tree.toString() : "null";
}
}
@@ -0,0 +1,69 @@
package com.baeldung.algorithms.balancedbinarytree;
import java.util.Arrays;
import java.util.Collection;
class BinaryTreeDataProvider {
static Collection<Tree> balancedTrees() {
return Arrays.asList(
null,
leaf(1),
tree(1, leaf(2), leaf(3)),
tree(
1,
leaf(2),
tree(3, leaf(4), null)
),
tree(
1,
tree(
2,
tree(3, leaf(4), null),
leaf(5)
),
tree(
6,
leaf(7),
tree(8, null, leaf(9))
)
)
);
}
static Collection<Tree> unbalancedTrees() {
return Arrays.asList(
tree(
1,
tree(2, leaf(3), null),
null
),
tree(
1,
tree(
2,
tree(3, leaf(4), leaf(5)),
null
),
tree(6, leaf(7), null)
),
tree(
1,
tree(2, leaf(3), null),
tree(
4,
tree(5, leaf(6), leaf(7)),
null
)
)
);
}
private static Tree leaf(int value) {
return new Tree(value, null, null);
}
private static Tree tree(int value, Tree left, Tree right) {
return new Tree(value, left, right);
}
}