Skip to content

Instantly share code, notes, and snippets.

@Anirudhk94
Created January 27, 2019 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anirudhk94/8ab65b4437167818083c431c51bb9aa7 to your computer and use it in GitHub Desktop.
Save Anirudhk94/8ab65b4437167818083c431c51bb9aa7 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null)
return result;
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
int min = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
Queue<Integer> index = new LinkedList<Integer>();
q.add(root);
index.add(min);
while(!q.isEmpty()) {
TreeNode current = q.remove();
int idx = index.remove();
if(!map.containsKey(idx))
map.put(idx, new ArrayList<Integer>());
map.get(idx).add(current.val);
if(current.left != null) {
q.add(current.left);
index.add(idx - 1);
}
if(current.right != null) {
q.add(current.right);
index.add(idx + 1);
}
min = Math.min(min, idx);
}
while(map.containsKey(min)) {
result.add(map.get(min));
min++;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment