import java.util.*; class BinarySearchTree> { private Node root; private int nodeCount = 0; void insert(T value) { if (root == null) { root = new Node<>(value); } else { insert(root, value); } nodeCount++; } List getAsSortedList() { List result = new ArrayList<>(nodeCount); putInSortedOrderToList(root, result); return Collections.unmodifiableList(result); } List getAsLevelOrderList() { List result = new ArrayList<>(nodeCount); putInLevelOrderToList(root, result); return Collections.unmodifiableList(result); } 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); } } } static class Node { private T data; private Node left = null; private Node right = null; Node(T data) { this.data = data; } Node getLeft() { return left; } void setLeft(Node left) { this.left = left; } Node getRight() { return right; } void setRight(Node right) { this.right = right; } T getData() { return data; } } }