Simple Java solution ( level order traversal)


  • 0
    A

    Simply find the max value of every level

    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if(root == null) {
                return list;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            list.add(root.val);
            int count = 0;
            while( !queue.isEmpty() ){
                int size = queue.size();
                int max = Integer.MIN_VALUE;
                count++;
                for(int i = 0; i < size; i++) {
                    
                    TreeNode cur = queue.poll();
    
                    if(cur.left != null) {
                        queue.offer(cur.left);
                        max = Math.max(cur.left.val, max);
                    }
                    
                    if(cur.right != null ) {
                        queue.offer(cur.right);
                        max = Math.max(cur.right.val, max);
                    }
                } 
                list.add(max);
            }
            list.remove(list.size() + (count - list.size()));
            return list;
        }
    }
    

Log in to reply
 

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