BinaryTreeEquals { public boolean areEqualsIterative(BinaryNode<Integer> tree1, BinaryNode<Integer> tree2) { validateInput(tree1, tree2); boolean equals = true; Stack<BinaryNode> stack1 = new Stack<BinaryNode>(); Stack<BinaryNode> stack2 = new Stack<BinaryNode>(); stack1.push(tree1); stack2.push(tree2); while (!stack1.isEmpty()) { BinaryNode node1 = stack1.pop(); BinaryNode node2 = stack2.pop(); if (!node1.equals(node2)) { equals = false; break; } addNodeToStack(stack1, node1.getLeft()); addNodeToStack(stack1, node1.getRight()); addNodeToStack(stack2, node2.getLeft()); addNodeToStack(stack2, node2.getRight()); } return equals; }  boolean areEqualsRecursive(BinaryNode tree1, BinaryNode tree2); boolean areEqualsIterative(BinaryNode<Integer> tree1, BinaryNode<Integer> tree2);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptTwoNullTreesIterative() { binaryTreeEquals.areEqualsIterative(null, null); }
@Test public void shouldReturnFalseIfOneIsNullIterative() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); assertFalse(binaryTreeEquals.areEqualsIterative(root, null)); }
@Test public void shouldReturnTrueIfBothElementsAreEqualsEvenIfJustContainsOneElementIterative() { BinaryNode<Integer> root = new BinaryNode<Integer>(0); BinaryNode<Integer> root1 = new BinaryNode<Integer>(0); assertTrue(binaryTreeEquals.areEqualsIterative(root, root1)); }
@Test public void shouldReturnFalseIfTreesAreNotEqualsIterative() { 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); BinaryNode<Integer> root1 = new BinaryNode<Integer>(0); BinaryNode<Integer> n11 = new BinaryNode<Integer>(1); BinaryNode<Integer> n21 = new BinaryNode<Integer>(2); BinaryNode<Integer> n31 = new BinaryNode<Integer>(3); root.setLeft(n11); root.setRight(n21); n21.setRight(n31); assertFalse(binaryTreeEquals.areEqualsIterative(root, root1)); }
@Test public void shouldReturnTrueIfTreesAreEqualsIterative() { 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); root.setLeft(n1); root.setRight(n2); n1.setLeft(n3); BinaryNode<Integer> root1 = new BinaryNode<Integer>(0); BinaryNode<Integer> n11 = new BinaryNode<Integer>(1); BinaryNode<Integer> n21 = new BinaryNode<Integer>(2); BinaryNode<Integer> n31 = new BinaryNode<Integer>(3); root.setLeft(n11); root.setRight(n21); n1.setLeft(n31); assertFalse(binaryTreeEquals.areEqualsIterative(root, root1)); }