Clean Java Solution


  • 0
    A
    class TreeNodeEx {
    	int level;
    	TreeNode node;
    	public TreeNodeEx(int level, TreeNode node) {
    		this.node = node;
    		this.level = level;
    	}
    }
    
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    	if (root == null) return new LinkedList<List<Integer>>();
    	Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
    	Deque<TreeNodeEx> queue = new LinkedList<TreeNodeEx>();
    	queue.offer(new TreeNodeEx(0, root));
    	while (!queue.isEmpty()) {
    		TreeNodeEx tnex = queue.remove();
    		if (map.get(tnex.level) == null) 
    		    map.put(tnex.level, new LinkedList<Integer>());
    		
    		if(tnex.level%2 == 0) map.get(tnex.level).add(tnex.node.val);
    		else map.get(tnex.level).add(0,tnex.node.val);
    		
    		if (tnex.node.left != null) queue.add(new TreeNodeEx(tnex.level + 1, tnex.node.left));
    		if (tnex.node.right != null) queue.add(new TreeNodeEx(tnex.level + 1, tnex.node.right));
    	}
    	return new LinkedList<List<Integer>>(map.values());
    }

Log in to reply
 

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