Clean Java Solution


  • 0
    A
    class TreeNodeEx {
    	int line;
    	TreeNode node;
    	public TreeNodeEx(int line, TreeNode node) {
    		this.node = node;
    		this.line = line;
    	}
    }
    
    public List<List<Integer>> verticalOrder(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.line) == null) map.put(tnex.line, new LinkedList<Integer>());
    		map.get(tnex.line).add(tnex.node.val);
    		if (tnex.node.left != null) queue.add(new TreeNodeEx(tnex.line - 1, tnex.node.left));
    		if (tnex.node.right != null) queue.add(new TreeNodeEx(tnex.line + 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.