clueless coding // TODO: be smarter

LeetCode Find Largest Value in Each Tree Row: Java Solution



TL;DR Code Solution


public List<Integer> largestValues(TreeNode root) {

    List<Integer> result = new LinkedList<Integer>();

    if (root == null) return result;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        int candidate = Integer.MIN_VALUE;
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode curr = queue.poll();
            if (curr.left != null) queue.offer(curr.left);
            if (curr.right != null) queue.offer(curr.right);
            candidate = Math.max(candidate, curr.val);
        }
        result.add(candidate);
    }

    return result;

}