Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 8, 2017 20:01
Show Gist options
  • Select an option

  • Save shailrshah/a2f9c9c63b8ecdd53e53d9318311ac07 to your computer and use it in GitHub Desktop.

Select an option

Save shailrshah/a2f9c9c63b8ecdd53e53d9318311ac07 to your computer and use it in GitHub Desktop.
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right.
/*
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
*/
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> cols = new ArrayList<>();
if(root == null)
return cols;
Map<Integer, List<Integer>> map = new HashMap<>();
Queue<TreeNode> nodeQueue = new LinkedList<>();
Queue<Integer> colQueue = new LinkedList<>();
int min = 0, max = 0;
nodeQueue.add(root);
colQueue.add(0);
while(nodeQueue.size() > 0) {
TreeNode currNode = nodeQueue.poll();
int currCol = colQueue.poll();
if(!map.containsKey(currCol))
map.put(currCol, new ArrayList<>());
map.get(currCol).add(currNode.val);
if(currNode.left!=null) {
nodeQueue.add(currNode.left);
colQueue.add(currCol - 1);
min = Math.min(min, currCol - 1);
}
if(currNode.right!=null) {
nodeQueue.add(currNode.right);
colQueue.add(currCol + 1);
max = Math.max(max, currCol + 1);
}
}
for(int i = min; i <= max; i++)
cols.add(map.get(i));
return cols;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment