Simple Recursion Java Solution Using LinkedList


  • 1
    X

    Just used type conversion.

     public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        helper(root,1,result);
        return result;
    }
    
    private void helper(TreeNode root, int level, List<List<Integer>> result){
        if(root!=null){
            if(result.size() < level) result.add(new LinkedList<Integer>());
            if(level%2 == 1) result.get(level-1).add(root.val);
            else ((LinkedList)result.get(level-1)).addFirst(root.val);
            helper(root.left,level+1,result);
            helper(root.right,level+1,result);
        }
    }
    

    }


  • 0

    Wow, this is brilliant!! Not a difficult problem, but it is really fun to watch your solution. Keep working.


  • 0
    X

    @Augustdoker Thanks AUG. Let's keep it up!


Log in to reply
 

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