Another approach in Java using preorder; beats 92%


  • 0
    L
           List<Integer> list = new ArrayList<>();
        public List<Integer> largestValues(TreeNode root) {
            if(root==null) {
                return Collections.EMPTY_LIST;    
            }
            helper(root,0);    
            return list;
        }
        
        private void helper(TreeNode root,int level) {
            if(root==null) {
                return;
            }
    
            if(list.size()<level+1) {
                list.add(root.val);
            }
            else {
                list.set(level,Math.max(root.val,list.get(level)));
            }
            helper(root.left,level+1);
            helper(root.right,level+1);
        }
    

Log in to reply
 

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