Easy BFS Solution


  • 1
    X
    public List<Integer> largestValues(TreeNode root) {
    
        Queue<TreeNode> q = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if(root == null) return res;
        
           
        q.add(root);
        int size = q.size();
        
        while(!q.isEmpty()){
    
            int levelMax = Integer.MIN_VALUE;
            for(int i = 0; i < size; i++){
              TreeNode node = q.poll();
                levelMax = Math.max(node.val, levelMax);
                
                if(node.left != null)
                    q.add(node.left);
                if(node.right != null)
                    q.add(node.right);
                
            } 
                res.add(levelMax);
                size = q.size();
        }
        return res;
        
    }

Log in to reply
 

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