class Node { private String _item; private Node _left, _right; public Node(String item, Node left, Node right) { _item = item; _left = left; _right = right; } public String item() { return _item; } public Node left() { return _left; } public Node right() { return _right; } public boolean isLeaf() { return _left == null && _right == null; } } class Tree { private Node _root = null; public boolean contains(String target) { return contains(_root, target); } protected boolean contains(Node n, String target) { if ( n == null ) return false; else if ( n._item.equals(target) ) return true; else if ( n.compareTo(target) < 0 ) return contains(n.left(), target); else return contains(n.right(), target); } public void add(String target) { ... code omitted ... } }
class Node { private String _item; private ArrayList<Node> _children = new ArrayList<>(); public Node(String item) { _item = item; } public add(Node n) { _children.add(n); } public String item() { return _item; } public Iterator<Node> childrenIterator() { return _children.iterator(); } public boolean isLeaf() { ...?... } }
abstract class Node { private String _item; public String item() { return _item; } public Node(String item) { _item = item; } abstract boolean isLeaf(); abstract void add(Node n); abstract Iterator<Node> childrenIterator(); } class Leaf extends Node { public Leaf(String i) { super(i); } public void add(Node n) { throw new UnsupportedOperationException("children not supported"); } public Iterator<Node> childrenIterator { return null; } public boolean isLeaf() { return true; } } class Branch extends Node { public Branch(String i) { super(i); } private ArrayList<Node> _children = new ArrayList<>(); public void add(Node n) { _children.add(n); } public Iterator<Node> childrenIterator { return _children.iterator(); } public boolean isLeaf() { return false; } }
ArrayList