package hellfirepvp.beebetteratbees.client.util; /** * HellFirePvP@Admin * Date: 29.04.2016 / 00:23 * on BeeBetterAtBees * SimpleBinaryTree */ public class SimpleBinaryTree { private Node root; private RootProvider rootProvider; public SimpleBinaryTree(int maxDepth, E rootValue, RootProvider provider) { this.rootProvider = provider; this.root = buildSubTree(rootValue, maxDepth); } public SimpleBinaryTree(E rootValue, RootProvider provider) { this(Integer.MAX_VALUE, rootValue, provider); } public Node getRoot() { return root; } private Node buildSubTree(E superNodeValue, int maxFollowingDepth) { if (maxFollowingDepth <= 0) { return new Leaf<>(superNodeValue); } E[] subNodes = rootProvider.provideSubNodes(superNodeValue); if(subNodes == null || subNodes.length == 0) { return new Leaf<>(superNodeValue); } else { Node left = buildSubTree(subNodes[0], maxFollowingDepth - 1); Node right = buildSubTree(subNodes[1], maxFollowingDepth - 1); int depth = Math.max(left.getMaxFollowingDepth(), right.getMaxFollowingDepth()); return new Node<>(superNodeValue, left, right, depth + 1); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleBinaryTree that = (SimpleBinaryTree) o; return !(root != null ? !root.equals(that.root) : that.root != null); } @Override public int hashCode() { return root != null ? root.hashCode() : 0; } public abstract static class RootProvider { public abstract E[] provideSubNodes(E superNode); } public static class Node { protected final E value; private int maxFollowingDepth; private Node left, right; private Node(E value, Node left, Node right, int depth) { this.value = value; this.left = left; this.right = right; this.maxFollowingDepth = depth; } public int getMaxFollowingDepth() { return maxFollowingDepth; } public E getValue() { return value; } public Node getLeftNode() { return left; } public Node getRightNode() { return right; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; return !(value != null ? !value.equals(node.value) : node.value != null); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } @Override public String toString() { return new StringBuilder().append("[").append(left.toString()) .append("], ").append(value.toString()).append(", [") .append(right.toString()).append("]").toString(); } public void removeDuplicate() { this.left = null; this.right = null; this.maxFollowingDepth = 1; } } private static class Leaf extends Node { private Leaf(E value) { super(value, null, null, 0); } @Override public String toString() { return value.toString(); } } }