/** * Creates a PostorderIterator. * * @param rootNode the root node for this iteration. */ private PostorderIterator(final TreeNode rootNode) { root = rootNode; children = root.children(); subtree = EMPTY_ITERATOR; }
/** * @return the next element in the iteration. */ @Override public TreeNode next() { Iterator<TreeNode> iterator = queue.firstObject(); TreeNode node = iterator.next(); Iterator<TreeNode> children = node.children(); if (!iterator.hasNext()) { queue.dequeue(); } if (children.hasNext()) { queue.enqueue(children); } return node; }
@Test public void testChildren() { // Test when no children TreeNode node = new TestNode(); Assert.assertFalse("Should not have any children", node.children().hasNext()); // Test when has children node = buildTestTree(); Iterator<TreeNode> children = node.children(); Assert.assertEquals("Incorrect child 1", "B", children.next().toString()); Assert.assertEquals("Incorrect child 2", "C", children.next().toString()); Assert.assertEquals("Incorrect child 3", "D", children.next().toString()); Assert.assertFalse("Incorrect number of children", children.hasNext()); }