Given a complete binary tree returns the following format (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) ). Looking for code review, optimizations and best practices.
public final class PreOrderList {
private TreeNode root;
/**
* Constructs a binary tree in order of elements in an array.
* The input list is treated as BFS representation of the list.
* Note that it is the clients responsibility to not modify input list in objects lifetime.
*
*/
PreOrderList(List<String> items) {
create (items);
}
private static class TreeNode {
TreeNode left;
String item;
TreeNode right;
TreeNode(TreeNode left, String item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private void create (List<String> items) {
root = new TreeNode(null, items.get(0), null);
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2; // http://stackoverflow.com/questions/21156774/unit-testing-complicated-methods-what-to-test-and-what-to-assume
if (items.get(left) != null) {
current.left = new TreeNode(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
/**
* Returns the string representation of the format
* (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) )
* It needs a complete balanced tree, else invalid format is be returned.
*
* @return the String representation.
*/
public String getPreorderList() {
if (root == null) {
throw new NoSuchElementException("The element cannot be null.");
}
final StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(root.item);
preOrder(root, sb);
sb.append(")");
return sb.toString();
}
private void preOrder(TreeNode node, StringBuilder sb) {
if (node.left != null) {
sb.append("(");
sb = sb.append(node.left.item);
preOrder(node.left, sb);
}
if (node.right != null) {
sb.append(",");
sb = sb.append(node.right.item + "");
preOrder(node.right, sb);
sb.append(")");
}
}
public static void main(String[] args) {
PreOrderList pol = new PreOrderList(new ArrayList<String>(Arrays.asList("1", "2", "3", "4", "5", "6", "7")));
assertEquals("(1(2(4,5),3(6,7)))", pol.getPreorderList());
}
}