Skip to content

Commit

Permalink
Merge pull request iluwatar#779 from mitchellirvin/bst-iterator
Browse files Browse the repository at this point in the history
iluwatar#778: Binary Search Tree Iterator
  • Loading branch information
npathai authored Aug 30, 2018
2 parents 74f3799 + 8458e42 commit 038befe
Show file tree
Hide file tree
Showing 15 changed files with 572 additions and 179 deletions.
Binary file added iterator/etc/bst.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 5 additions & 5 deletions iterator/etc/iterator.ucls
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.iterator.TreasureChest" project="iterator"
<class id="1" language="java" name="com.iluwatar.iterator.list.TreasureChest" project="iterator"
file="/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java" binary="false" corner="BOTTOM_RIGHT">
<position height="124" width="195" x="1" y="237"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
Expand All @@ -10,7 +10,7 @@
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.iterator.Item" project="iterator"
<class id="2" language="java" name="com.iluwatar.iterator.list.Item" project="iterator"
file="/iterator/src/main/java/com/iluwatar/iterator/Item.java" binary="false" corner="BOTTOM_RIGHT">
<position height="160" width="157" x="195" y="401"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
Expand All @@ -19,7 +19,7 @@
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<enumeration id="3" language="java" name="com.iluwatar.iterator.ItemType" project="iterator"
<enumeration id="3" language="java" name="com.iluwatar.iterator.list.ItemType" project="iterator"
file="/iterator/src/main/java/com/iluwatar/iterator/ItemType.java" binary="false" corner="BOTTOM_RIGHT">
<position height="160" width="145" x="388" y="601"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
Expand All @@ -28,7 +28,7 @@
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</enumeration>
<interface id="4" language="java" name="com.iluwatar.iterator.ItemIterator" project="iterator"
<interface id="4" language="java" name="com.iluwatar.iterator.list.ItemIterator" project="iterator"
file="/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java" binary="false" corner="BOTTOM_RIGHT">
<position height="106" width="131" x="236" y="237"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
Expand All @@ -37,7 +37,7 @@
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
<class id="5" language="java" name="com.iluwatar.iterator.TreasureChestItemIterator" project="iterator"
<class id="5" language="java" name="com.iluwatar.iterator.list.TreasureChestItemIterator" project="iterator"
file="/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="160" width="323" x="236" y="37"/>
Expand Down
107 changes: 63 additions & 44 deletions iterator/src/main/java/com/iluwatar/iterator/App.java
Original file line number Diff line number Diff line change
@@ -1,76 +1,95 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* The MIT License Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.iluwatar.iterator;

import static com.iluwatar.iterator.list.ItemType.ANY;
import static com.iluwatar.iterator.list.ItemType.POTION;
import static com.iluwatar.iterator.list.ItemType.RING;
import static com.iluwatar.iterator.list.ItemType.WEAPON;

import com.iluwatar.iterator.bst.BstIterator;
import com.iluwatar.iterator.bst.TreeNode;
import com.iluwatar.iterator.list.Item;
import com.iluwatar.iterator.list.ItemType;
import com.iluwatar.iterator.list.TreasureChest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
*
* The Iterator pattern is a design pattern in which an iterator is used to traverse a container and
* access the container's elements. The Iterator pattern decouples algorithms from containers.
* <p>
* In this example the Iterator ({@link ItemIterator}) adds abstraction layer on top of a collection
* In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection
* ({@link TreasureChest}). This way the collection can change its internal implementation without
* affecting its clients.
*
*/
public class App {

private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
TreasureChest chest = new TreasureChest();
private static final TreasureChest TREASURE_CHEST = new TreasureChest();

ItemIterator ringIterator = chest.iterator(ItemType.RING);
while (ringIterator.hasNext()) {
LOGGER.info(ringIterator.next().toString());
private static void demonstrateTreasureChestIteratorForType(ItemType itemType) {
LOGGER.info("------------------------");
LOGGER.info("Item Iterator for ItemType " + itemType + ": ");
Iterator<Item> itemIterator = TREASURE_CHEST.iterator(itemType);
while (itemIterator.hasNext()) {
LOGGER.info(itemIterator.next().toString());
}
}

LOGGER.info("----------");

ItemIterator potionIterator = chest.iterator(ItemType.POTION);
while (potionIterator.hasNext()) {
LOGGER.info(potionIterator.next().toString());
private static void demonstrateBstIterator() {
LOGGER.info("------------------------");
LOGGER.info("BST Iterator: ");
TreeNode<Integer> root = buildIntegerBst();
BstIterator bstIterator = new BstIterator<>(root);
while (bstIterator.hasNext()) {
LOGGER.info("Next node: " + bstIterator.next().getVal());
}
}

LOGGER.info("----------");
private static TreeNode<Integer> buildIntegerBst() {
TreeNode<Integer> root = new TreeNode<>(8);

ItemIterator weaponIterator = chest.iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) {
LOGGER.info(weaponIterator.next().toString());
}
root.insert(3);
root.insert(10);
root.insert(1);
root.insert(6);
root.insert(14);
root.insert(4);
root.insert(7);
root.insert(13);

LOGGER.info("----------");
return root;
}

ItemIterator it = chest.iterator(ItemType.ANY);
while (it.hasNext()) {
LOGGER.info(it.next().toString());
}
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
demonstrateTreasureChestIteratorForType(RING);
demonstrateTreasureChestIteratorForType(POTION);
demonstrateTreasureChestIteratorForType(WEAPON);
demonstrateTreasureChestIteratorForType(ANY);

demonstrateBstIterator();
}
}
35 changes: 0 additions & 35 deletions iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java

This file was deleted.

30 changes: 30 additions & 0 deletions iterator/src/main/java/com/iluwatar/iterator/Iterator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* The MIT License Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.iluwatar.iterator;

/**
* Iterator interface to be implemented by iterators over various data structures
* @param <T> generically typed for various objects
*/
public interface Iterator<T> {

boolean hasNext();

T next();
}
77 changes: 77 additions & 0 deletions iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* The MIT License Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.iluwatar.iterator.bst;

import com.iluwatar.iterator.Iterator;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;

/**
* An in-order implementation of a BST Iterator. For example, given a BST with Integer values,
* expect to retrieve TreeNodes according to the Integer's natural ordering (1, 2, 3...)
*
* @param <T> This Iterator has been implemented with generic typing to allow for TreeNodes of
* different value types
*/
public class BstIterator<T extends Comparable<T>> implements Iterator<TreeNode<T>> {

private ArrayDeque<TreeNode<T>> pathStack;

public BstIterator(TreeNode<T> root) {
pathStack = new ArrayDeque<>();
pushPathToNextSmallest(root);
}

/**
* This BstIterator manages to use O(h) extra space, where h is the height of the tree It achieves
* this by maintaining a stack of the nodes to handle (pushing all left nodes first), before
* handling self or right node
*
* @param node TreeNode that acts as root of the subtree we're interested in.
*/
private void pushPathToNextSmallest(TreeNode<T> node) {
while (node != null) {
pathStack.push(node);
node = node.getLeft();
}
}

/**
* @return true if this iterator has a "next" element
*/
@Override
public boolean hasNext() {
return !pathStack.isEmpty();
}

/**
* @return TreeNode next. The next element according to our in-order traversal of the given BST
* @throws NoSuchElementException if this iterator does not have a next element
*/
@Override
public TreeNode<T> next() throws NoSuchElementException {
if (pathStack.isEmpty()) {
throw new NoSuchElementException();
}
TreeNode<T> next = pathStack.pop();
pushPathToNextSmallest(next.getRight());
return next;
}

}
Loading

0 comments on commit 038befe

Please sign in to comment.