Created
January 27, 2019 02:42
-
-
Save Anirudhk94/8ab65b4437167818083c431c51bb9aa7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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