Beats around 77% of all Java Solutions


  • 0
    R
        public List<Integer> largestValues(TreeNode root) {
            if(root==null) {
                return new ArrayList<>();
            }
            List<Integer> list = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            list.add(root.val);
            queue.add(root);
            return a(queue, list);
            
        }
        
        public List<Integer> a(Queue<TreeNode> queue, List<Integer> list) {
            
            if(queue.isEmpty()) {
                return list;
            }
            int max = Integer.MIN_VALUE;
            boolean found = false;
            Queue<TreeNode> q = new LinkedList<>();
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if(node.left!=null) {
                    found = true;
                    q.add(node.left);
                    max = Math.max(max, node.left.val);
                }
                if(node.right!=null) {
                    found = true;
                    q.add(node.right);
                    max = Math.max(max, node.right.val);
                }
            }
            if(max > Integer.MIN_VALUE || found) {
                list.add(max);    
            }
            return a(q, list);
        }
    

Log in to reply
 

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