My java solusion


  • 0
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {	
    	int count = 0;
    	List<List<Integer>> result = new LinkedList<List<Integer>>();    	
    	Queue<TreeNode> queue = new LinkedList<>();
    	if (root==null) {
    		return result;
    	}
    	queue.offer(root);
    	while (!queue.isEmpty()) {
    		count += 1;
    		int size = queue.size();
    		List<Integer> temp = new LinkedList<>();
    		for(int i=0;i<size;i++){
    			TreeNode cur = queue.poll();
    			temp.add(cur.val);
    			if(cur.left!=null) queue.add(cur.left);		
    			if(cur.right!=null) queue.add(cur.right);    			
    		}
    		if(count%2!=0) result.add(temp);
    		else {
    			Collections.reverse(temp);
    			result.add(temp);
    		}
    	}  	
    	return result;       
    }

  • 0

    it is easy to understand


Log in to reply
 

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