Simple Java BFS


  • 0
    H
       public List<Integer> largestValues(TreeNode root) {
            Queue<TreeNode> q= new LinkedList();
            List<Integer> list= new ArrayList();
            if(root==null) return list;
             q.offer(root);
             while(!q.isEmpty()){
                 int max= Integer.MIN_VALUE;
                 int s=q.size();
                 while(s-->0){
                     TreeNode node= q.poll();
                     if(node.val>max) max=node.val;
                     if(node.left!=null) q.offer(node.left);
                     if(node.right!=null) q.offer(node.right);
                 }
                 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.