Java,levelOrder


  • 1
    public List<Integer> largestValues(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if (root == null)
                return list;
    
            LinkedList<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
    
            while (!queue.isEmpty()) {
    
                int len = queue.size();
                int max = Integer.MIN_VALUE;
    
                for (int i = 0; i < len; i++) {
    
                    TreeNode t = queue.poll();
                    max = Math.max(max, t.val);
                    if (t.left != null)
                        queue.offer(t.left);
                    if (t.right != null)
                        queue.offer(t.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.