Left view of a Binary Tree is set of nodes visible when tree is visited from left side. Left view of following tree is 12, 10, 25.
12
/ \
10 30
/ \
25 40
Looking for code review, optimizations and best practices. Also verifying space complexity is O(n) and not O(logn) where n is number of nodes in tree.
public class LeftView<T> {
private TreeNode<T> root;
/**
* Takes in a BFS representation of a tree, and converts it into a tree.
* here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd
* positions respectively.
*
* @param items The items to be node values.
*/
public LeftView(List<? extends T> items) {
create(items);
}
private void create (List<? extends T> items) {
root = new TreeNode<T>(null, items.get(0), null);
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>(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<T>(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
private static class TreeNode<E> {
TreeNode<E> left;
E item;
TreeNode<E> right;
TreeNode(TreeNode<E> left, E item, TreeNode<E> right) {
this.left = left;
this.item = item;
this.right = right;
}
}
/**
* Returns the left view of the binary tree
*
* @return the left view of binary tree.
*/
public List<T> leftView() {
if (root == null) { throw new NoSuchElementException("The root is null"); }
final List<T> leftView = new ArrayList<T>();
computeLeftView(root, leftView, 1);
return leftView;
}
private void computeLeftView(TreeNode<T> node, List<T> leftView, int currentDepth) {
if (node != null) {
if (currentDepth > leftView.size()) {
leftView.add(node.item);
}
computeLeftView(node.left, leftView, currentDepth + 1);
computeLeftView(node.right, leftView, currentDepth + 1);
}
}
public static void main(String[] args) {
final LeftView<Integer> leftView1 = new LeftView<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
assertEquals(Arrays.asList(1, 2, 4) , leftView1.leftView());
final LeftView<Integer> leftView2 = new LeftView<Integer>(Arrays.asList(1, 2, 3, 4, null, 6, 7));
assertEquals(Arrays.asList(1, 2, 4) , leftView2.leftView());
final LeftView<Integer> leftView3 = new LeftView<Integer>(Arrays.asList(1, 2, 3, null, 5, 6, 7));
assertEquals(Arrays.asList(1, 2, 5) , leftView3.leftView());
final LeftView<Integer> leftView4 = new LeftView<Integer>(Arrays.asList(1, 2, 3, null, null, 6, 7));
assertEquals(Arrays.asList(1, 2, 6) , leftView4.leftView());
}
}
public static List<T> leftView(BinaryTree<T>)
. \$\endgroup\$