Simple Java solution using level-order search


  • 0
    L
    public List<Integer> largestValues(TreeNode root) {
            
            if(root==null) {
                return Collections.EMPTY_LIST;    
            }
            
            List<Integer> list = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()) {
                int size=queue.size();
                int max = Integer.MIN_VALUE;
                while(size>0) {
                    TreeNode node = queue.poll();
                    if(node.left!=null) {
                        queue.add(node.left);
                    }
                    if(node.right!=null) {
                        queue.add(node.right);
                    }
                    max = Math.max(max,node.val);
                    size--;
                }
                list.add(max);
            }
            return list;
        }
    

Log in to reply
 

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