Check if all leaves are at same level. This question is attributed to geek for geeks. Looking for code-review, optimization and best practices.
public class LeavesLevel<T> {
private TreeNode<T> root;
public LeavesLevel(List<T> items) {
create (items);
}
private void create (List<T> items) {
root = new TreeNode<>(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();
final int left = 2 * i + 1;
final 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 boolean refurbish() {
return recurse (root, 0, new NodeDepth(-1));
}
private static class NodeDepth {
private int depth;
NodeDepth(int depth) {
this.depth = depth;
}
}
public boolean recurse(TreeNode<T> node, int leafLevel, NodeDepth nodeDepth) {
if (node == null) {
return true;
}
if (node.left == null && node.right == null) {
if (nodeDepth.depth == -1) {
nodeDepth.depth = leafLevel;
return true; // if tree contains a single leaf node, then
}
return leafLevel == nodeDepth.depth;
}
return recurse (node.left, leafLevel + 1, nodeDepth) && recurse (node.right, leafLevel + 1, nodeDepth);
}
}
public class LeafLevelTest {
@Test
public void test1() {
/**
*
* 12
/ \
5 7
/ \
3 1
*
*/
LeavesLevel<Integer> ll1 = new LeavesLevel<>(Arrays.asList(1, 5, 7, 3, null, null, 1));
assertTrue(ll1.refurbish());
}
@Test
public void test2() {
/**
* 12
/ \
5 7
/
3
*
*/
LeavesLevel<Integer> ll2 = new LeavesLevel<>(Arrays.asList(1, 5, 7, 3));
assertFalse(ll2.refurbish());
}
@Test
public void test3() {
/**
*
*
12
/
5
/ \
3 9
/ /
1 2
*
*
*/
LeavesLevel<Integer> ll3 = new LeavesLevel<>(Arrays.asList(1, 5, null, 3, 9, null, null, 1, null, 2));
assertTrue(ll3.refurbish());
}
}