import java.lang.*; abstract class TreeNode { public int key; public TreeNode leftchild; public TreeNode rightchild; public TreeNode(int k, TreeNode left, TreeNode right) { key = k; leftchild = left; rightchild = right; } public abstract void accept(Visitor v); } class BlueNode extends TreeNode { public BlueNode(int k, TreeNode left, TreeNode right) { super(k, left, right); } public void accept(Visitor v) { v.blueNode(this); } } class GreenNode extends TreeNode { public GreenNode(int k, TreeNode left, TreeNode right) { super(k, left, right); } public void accept(Visitor v) { v.greenNode(this); } } class Visitor { public void blueNode(BlueNode node) { System.out.print(node.key + ": "); System.out.println("Blue"); if (node.leftchild != null) node.leftchild.accept(this); if (node.rightchild != null) node.rightchild.accept(this); } public void greenNode(GreenNode node) { System.out.print(node.key + ": "); System.out.println("Green"); if (node.leftchild != null) node.leftchild.accept(this); if (node.rightchild != null) node.rightchild.accept(this); } } public class VisitorPattern { public static void main(String [] args) { TreeNode root = new BlueNode(1, new GreenNode(21, new BlueNode(31, null, null), new GreenNode(32, null, null)), new GreenNode(22, new BlueNode(33, null, null), new GreenNode(34, null, null))); root.accept(new Visitor()); } }