Why do I get this error "method levelOrder in class cannot be applied to given types"


  • 0
    public class Solution {
       HashMap<Integer, ArrayList<Integer>> map;
    	
    	public Solution()
    	{
    		map = new HashMap<Integer, ArrayList<Integer>>();
    	}
    	
    	public List<List<Integer>> levelOrderBottom(TreeNode root) 
    	{
    		levelOrder(root, 0);
    		
    		Integer[] keys = new Integer[map.keySet().size()];
    		int j=0;
    		for(Integer val:map.keySet())
    		{
    			keys[j++] = val;
    		}
    		Arrays.sort(keys);
    		
    		// Why this does not work: 
    		// List<List<Integer>> result = new ArrayList<ArrayList<Integer>>();
    		List<List<Integer>> result = new ArrayList<List<Integer>>();
    		for(int i=keys.length-1; i>=0; i--)
    		{
    			result.add(map.get(keys[i]));
    		}
    		
    		return result; 
    	}
    	
    	private void levelOrder(TreeNode root, int level)
    	{
    		if(root==null) return;
    		
    		levelOrder(root.left, level+1);
    		levelOrder(root.right, level+1);
    		addToList(root, level);
    	}
    	
    	private void addToList(TreeNode node, int level)
    	{
    		if(!map.containsKey(level))
    		{
    			ArrayList<Integer> list = new ArrayList<Integer>();
    			map.put(level, list);
    		}
    		
    		List<Integer> list = map.get(level);
    		list.add(node.val);
    	}
    }

  • 0
    M

    You renamed levelOrder(TreeNode root) to levelOrderBottom(TreeNode root) in your code, but the tester is assuming that the original method name exists. It is provided to you because it uses that method to enter the Solution class. Because you've changed levelOrder(TreeNode root) to levelOrderBottom(TreeNode root) and added levelOrder(TreeNode root, int level), the tester sends levelOrder(root) to levelOrder(TreeNode root, int level) and crashes since it doesn't match the correct number of parameters.

    You need to change the names of the methods so that levelOrder(TreeNode root) still exists and is the start of your program. The simplest way to do this is to change the name of levelOrderBottom(TreeNode root) back to levelOrder(TreeNode root). You do not need to change levelOrder(TreeNode root, int level). Due to function overloading, the number of parameters is enough to distinguish between the two and the tester will be able to run.


  • 0
    P

    Thanks. I didn't notice that I've changed the original method name.


Log in to reply
 

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