What's wrong with my levelOrder ? (java)


  • 0
    Y
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> path = new ArrayList<ArrayList<Integer>>();
            preOrder(root, 0, path);
            return path;
        }
        private void preOrder(TreeNode node, int level, ArrayList<ArrayList<Integer>> path) {
            if (node != null) {
                if (path.size() == level) {
                    ArrayList<Integer> tmp = new ArrayList<Integer>();
                    path.add(tmp);
                }
                path.get(level).add(node.val);
                preOrder(node.left, level + 1, path);
                proOrder(node.right, level + 1, path);
            }
        }
    }
    
    
    
    error: line 12: mismatched type.
    I can't see where is wrong??????

  • 0
    M

    How did it go beyond Line 3. It should give a compiler error at Line 3 itself!


  • 0
    Y

    Actually you are wrong. You can try it and see what happens.


  • 0
    M

    It should not go beyond line 3 because you cannot instantiate a List<List<Integer>> object as ArrayList<ArrayList<Integer>>

    Change your code to:

    public class Solution {
            public List<List<Integer>> levelOrder(TreeNode root) {
                List<List<Integer>> path = new ArrayList<List<Integer>>();
                preOrder(root, 0, path);
                return path;
            }
            private void preOrder(TreeNode node, int level, List<List<Integer>> path) {
                if (node != null) {
                    if (path.size() == level) {
                        ArrayList<Integer> tmp = new ArrayList<Integer>();
                        path.add(tmp);
                    }
                    path.get(level).add(node.val);
                    preOrder(node.left, level + 1, path);
                    preOrder(node.right, level + 1, path);
                }
            }
        }
    

Log in to reply
 

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