Share my simple Java solution


  • 0
    G

    public class Solution {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root == null){ return result;}
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        boolean reverseOrder = false;
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> levelResult = new ArrayList<Integer>();
            for(int i = 0; i < size; i++){
                TreeNode temp = queue.remove();
                levelResult.add(temp.val);
                if(temp.left != null){ queue.add(temp.left);}
                if(temp.right != null){ queue.add(temp.right);}
            }
            if(reverseOrder){
                Collections.reverse(levelResult);
            }
            result.add(levelResult);
            reverseOrder = !reverseOrder;
        }
        return result;
    }
    

    }


Log in to reply
 

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