Accepted Java solution. Recursion.


  • 0
    P

    LinkedList helps here to get zig-zag order. If the level is even add as last element. If odd add as first.

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

  • 0
    N

    how about change
    if (result.size()-1 < level)
    to
    if (result.size() == level)


Log in to reply
 

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