1 ms simple recursive JAVA solution beat 95%


  • 0
    D
    private List<List<Integer>> list;
    
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        list = new ArrayList<>();
        helper(root,1);
        return list;
    }
    
    
    public void helper(TreeNode root, int level){
        if(root==null)
            return;
        if(list.size()<level){
            List<Integer> curr = new ArrayList<>();
            list.add(curr);
        }
        if(level % 2 ==1)
            list.get(level-1).add(root.val);
        else
            list.get(level-1).add(0,root.val);
        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.