JAVA Easy Solution with no recursion


  • 0
    J
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            if (root == null) return new ArrayList<Integer>();
            Queue<TreeNode> queue = new LinkedList<>();
            int res = Integer.MIN_VALUE;
            ArrayList<Integer> list = new ArrayList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                res = Integer.MIN_VALUE;
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    if (node.val > res) res = node.val;
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
                
                list.add(res);
            }
            
            return list;
        }
    }

Log in to reply
 

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