import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class BinarySearchTree> { public static class Node { private T data; private Node left = null; private Node right = null; public Node(T data) { this.data = data; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public T getData() { return data; } } private Node root; private int nodeCount = 0; public void insert(T value) { if (root == null) { root = new Node<>(value); } else { this.insert(this.root, value); } this.nodeCount++; } public List getAsSortedList() { List result = new ArrayList<>(this.nodeCount); this.putInSortedOrderToList(this.root, result); return Collections.unmodifiableList(result); } public List getAsLevelOrderList() { List result = new ArrayList<>(this.nodeCount); this.putInLevelOrderToList(this.root, result); return Collections.unmodifiableList(result); } public Node getRoot() { return root; } private void insert(Node node, T value) { if (value.compareTo(node.getData()) <= 0) { if (node.getLeft() == null) { node.setLeft(new Node(value)); } else { insert(node.getLeft(), value); } } else { if (node.getRight() == null) { node.setRight(new Node(value)); } else { insert(node.getRight(), value); } } } private void putInSortedOrderToList(Node node, List list) { if (node == null || list == null) { return; } if (node.getLeft() != null) { putInSortedOrderToList(node.getLeft(), list); } list.add(node.getData()); if (node.getRight() != null) { putInSortedOrderToList(node.getRight(), list); } } private void putInLevelOrderToList(Node node, List list) { if (node == null || list == null) { return; } final Queue> queue = new LinkedList<>(); Node myNode; Node left; Node right; queue.add(node); while (!queue.isEmpty()) { myNode = queue.poll(); list.add(myNode.getData()); left = myNode.getLeft(); right = myNode.getRight(); if (left != null) { queue.add(left); } if (right != null) { queue.add(right); } } } }