BinaryTreeByLevel { public List<BinaryNode> getUsingQueue(BinaryNode root) { validateBinaryNode(root); List<BinaryNode> result = new LinkedList<BinaryNode>(); Queue<BinaryNode> queue = new LinkedList<BinaryNode>(); queue.add(root); while (!queue.isEmpty()) { BinaryNode binaryNode = queue.remove(); result.add(binaryNode); if (binaryNode.getLeft() != null) queue.add(binaryNode.getLeft()); if (binaryNode.getRight() != null) queue.add(binaryNode.getRight()); } return result; }  List<BinaryNode> getUsingQueue(BinaryNode root); List<BinaryNode> getWithoutAdditionalDataStructures(BinaryNode root);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullBinaryNodesUsingQueue() { binaryTreeByLevel.getUsingQueue(null); }
@Test public void shouldReturnTheSameNodeInTheListIfTheTreeJustContainsOneElementUsingQueue() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); List<BinaryNode> result = binaryTreeByLevel.getUsingQueue(root); List<BinaryNode<Integer>> expectedList = Arrays.asList(root); assertEquals(expectedList, result); }
@Test public void shouldWorkWithALittleBinaryTreeUsingQueue() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); BinaryNode<Integer> n1 = new BinaryNode<Integer>(1); BinaryNode<Integer> n2 = new BinaryNode<Integer>(2); root.setLeft(n1); root.setRight(n2); List<BinaryNode> result = binaryTreeByLevel.getUsingQueue(root); List<BinaryNode<Integer>> expectedList = Arrays.asList(root, n1, n2); assertEquals(expectedList, result); }
@Test public void shouldWorkWithABiggerBinaryTreeUsingQueue() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); BinaryNode<Integer> n1 = new BinaryNode<Integer>(1); BinaryNode<Integer> n2 = new BinaryNode<Integer>(2); BinaryNode<Integer> n3 = new BinaryNode<Integer>(3); BinaryNode<Integer> n4 = new BinaryNode<Integer>(4); BinaryNode<Integer> n5 = new BinaryNode<Integer>(5); root.setLeft(n1); root.setRight(n2); n1.setLeft(n3); n1.setRight(n4); n2.setLeft(n5); List<BinaryNode> result = binaryTreeByLevel.getUsingQueue(root); List<BinaryNode<Integer>> expectedList = Arrays.asList(root, n1, n2, n3, n4, n5); assertEquals(expectedList, result); }