Java Simple Iterative BFS


  • 0
    H
        public List<Integer> largestValues(TreeNode root) {
            if(root == null) return new ArrayList<>();
            
            int max = Integer.MIN_VALUE;
            int len = 0;
            List<Integer> ans = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            
            queue.add(root);
            
            while(!queue.isEmpty()){
                len = queue.size();
                max = Integer.MIN_VALUE;
                
                for(int i = 0; i < len; i++){
                    TreeNode cur = queue.poll();
                    max = Math.max(max, cur.val);
                    if(cur.left != null) queue.add(cur.left);
                    if(cur.right != null) queue.add(cur.right);
                }
                ans.add(max);
            }
            
            return ans;
        }

Log in to reply
 

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