Java

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**

 You need to find the largest value in each row of a binary tree.

 Example:
 Input:

    1
   / \
  3   2
 / \   \
5   3   9

 Output: [1, 3, 9]

 */

public class Find_Largest_Value_in_Each_Tree_Row {

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> largestValues(TreeNode root) {

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

            // bfs
            if (root == null) {
                return result;
            }

            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            int currentLevelCount = 1;
            int nextLevelCount = 0;

            int currentLevelMax = root.val;

            while (!q.isEmpty()) {
                TreeNode current = q.poll();
                currentLevelCount--;

                // check leftmost
                currentLevelMax = Math.max(currentLevelMax, current.val);

                if (current.left != null) {
                    q.offer(current.left);
                    nextLevelCount++;
                }
                if (current.right != null) {
                    q.offer(current.right);
                    nextLevelCount++;
                }

                if (currentLevelCount == 0) {
                    currentLevelCount = nextLevelCount;
                    nextLevelCount = 0;

                    result.add(currentLevelMax);

                    // reset
                    currentLevelMax = Integer.MIN_VALUE;
                }
            }

            return result;
        }
    }
}

All Problems

All Solutions