Java solution using BFS


  • 0
    C

    level order traversal using queue, and for each level, record the largest value

    /**
     * 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> ans = new ArrayList<Integer>();
            if (root == null) {
                return ans;
            }
            
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            
            while (!queue.isEmpty()) {
                int size = queue.size();
                int maxVal = Integer.MIN_VALUE;
                for (int i = 0; i < size; i++) {
                    TreeNode cur = queue.poll();
                    if (cur.left != null) {
                        queue.offer(cur.left);
                    }
                    if (cur.right != null) {
                        queue.offer(cur.right);
                    }
                    maxVal = Math.max(maxVal, cur.val);
                }
                ans.add(maxVal);
            }
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.