1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
Width of a tree is maximum of widths of all levels.
For the above tree:
- width of level 1 is 1
- width of level 2 is 2
- width of level 3 is 3
- width of level 4 is 2
So the maximum width of the tree is 3.
This code is attributed to GeeksForGeeks. I'm looking for code-review, best practices and optimizations. I'm verifying space complexity to be \$O(n)\$.
public class MaxWidthOfTree<T> {
private TreeNode<T> root;
public MaxWidthOfTree(List<T> items) {
create(items);
};
private void create(List<T> items) {
if (items.isEmpty()) {
throw new NullPointerException("The input array is not empty.");
}
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<>(items.get(left));
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<>(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 int getMaxWidth() {
if (root == null) {
throw new IllegalArgumentException("The root is empty");
}
int h = getHeight(root);
int[] arr = new int[h + 1]; // NOTE: h + 1
computeWidth(root, arr, 0);
return maxElementOfArray (arr);
}
private int maxElementOfArray(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
private void computeWidth(TreeNode<T> node, int[] arr, int level) {
if (node == null) return;
arr[level]++; // NOTE: you can place this as preorder, inorder or postorder, does not matter.
computeWidth(node.left, arr, level + 1);
computeWidth(node.right, arr, level + 1);
}
public int getHeight(TreeNode<T> node) {
if (node == null) return -1;
return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
}
}
public class MaxWidthOfTreeTest {
@Test
public void testLevel3() {
MaxWidthOfTree<Integer> mwot1 = new MaxWidthOfTree<>(Arrays.asList(1, 2, 3, 4, 5, null, 7, null, null, null, null, null, null, 14, 15));
assertEquals(3, mwot1.getMaxWidth());
}
@Test
public void testTestLevel4() {
MaxWidthOfTree<Integer> mwot2 = new MaxWidthOfTree<>(Arrays.asList(1, 2, 3, 4, 5, null, 7, null, null, 14, 15, null, null, 16, 17));
assertEquals(4, mwot2.getMaxWidth());
}
}