can't not figure out why they have such big different


  • 0
    Y

    My first solution is:
    public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    // write your code here
    List<List<Integer>> res = new ArrayList<>();
    if (root == null) {
    return res;
    }
    dfs(res, root, 0);
    return res;
    }

    private void dfs(List<List<Integer>> res, TreeNode root, int level) {
        if(root == null) {
            return;
        }
        if (level < res.size()) {
            List<Integer> nums = res.get(level);
            if (level % 2 == 0) {
                nums.add(root.val);
            }
            else {
               nums.add(0, root.val); 
            }
       }
       else {
            List<Integer> nums = new LinkedList<>();
            nums.add(root.val);
            res.add(nums);
        }
        dfs(res, root.left, level + 1);
        dfs(res, root.right, level + 1);
    }
    

    }
    In my second solution, I change the order of if statement in dfs method like this:

        if (level >= res.size()) {
            List<Integer> nums = new LinkedList<>();
            nums.add(root.val);
            res.add(nums);
        }
        else {
            List<Integer> nums = res.get(level);
            if (level % 2 == 0) {
                nums.add(root.val);
            }
            else {
               nums.add(0, root.val); 
            }
        }
    

    It run much faster than the first one, Does anyone know what happened here?


Log in to reply
 

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