Find all nodes of trees, without siblings.
This question is attributed to GeeksForGeeks.
I'm looking for code reviews, optimizations and best practices.
public class PrintNodesWithoutSiblings<T> {
private TreeNode<T> root;
public PrintNodesWithoutSiblings(List<T> items) {
create(items);
}
private void create (List<T> items) {
root = new TreeNode<T>(items.get(0));
final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<T> current = queue.poll();
int left = 2 * i + 1;
int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<T>(items.get(left));
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<T>(items.get(right));
queue.add(current.right);
}
}
}
}
private static class TreeNode<T> {
private TreeNode<T> left;
private T item;
private TreeNode<T> right;
TreeNode(T item) {
this.item = item;
}
}
public List<T> nonSiblingNodes() {
if (root == null) {
throw new IllegalStateException("Empty tree. Tree cannot be empty.");
}
final List<T> list = new ArrayList<T>();
findNonSiblingNodes(root, list);
return list;
}
private void findNonSiblingNodes(TreeNode<T> node, List<T> list) {
if (node == null) {
return;
}
if (node.left != null && node.right != null) {
findNonSiblingNodes(node.left, list);
findNonSiblingNodes(node.right, list);
} else if (node.left != null) {
list.add(node.left.item);
findNonSiblingNodes(node.left, list);
} else if (node.right != null) {
list.add(node.right.item);
findNonSiblingNodes(node.right, list);
}
}
}
public class PrintNodesWithoutSiblingTest {
@Test
public void test1() {
PrintNodesWithoutSiblings<Integer> ps1 = new PrintNodesWithoutSiblings<Integer>(Arrays.asList(1, 2, 3, 4, null, 6, null));
assertTrue(Arrays.asList(4, 6).equals(ps1.nonSiblingNodes()));
}
@Test
public void test2() {
PrintNodesWithoutSiblings<Integer> ps2 = new PrintNodesWithoutSiblings<Integer>(Arrays.asList(1, 2, null, 4, null, null, null));
assertTrue(Arrays.asList(2, 4).equals(ps2.nonSiblingNodes()));
}
}