BinaryTreePreOrder { public List<BinaryNode> getIterative(BinaryNode root) { validateBinaryNode(root); List<BinaryNode> result = new LinkedList<BinaryNode>(); Stack<BinaryNode> stack = new Stack<BinaryNode>(); stack.push(root); while (!stack.isEmpty()) { BinaryNode node = stack.pop(); result.add(node); if (node.hasRight()) { stack.add(node.getRight()); } if (node.hasLeft()) { stack.add(node.getLeft()); } } return result; }  List<BinaryNode> getRecursive(BinaryNode root); List<BinaryNode> getIterative(BinaryNode root);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullBinaryNodesIterative() { binaryTreePreOrder.getIterative(null); }
@Test public void shouldReturnJustOneElementIfTheTreeContainsJustOneElementIterative() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); List<BinaryNode> result = binaryTreePreOrder.getIterative(root); List<BinaryNode<Integer>> expected = Arrays.asList(root); assertEquals(expected, result); }
@Test public void shouldReturnBinaryNodesInPreOrderIterative() { 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); root.setLeft(n1); root.setRight(n2); n1.setLeft(n3); n1.setRight(n4); List<BinaryNode> result = binaryTreePreOrder.getIterative(root); List<BinaryNode<Integer>> expected = Arrays.asList(root, n1, n3, n4, n2); assertEquals(expected, result); }