标签:node Binary Vertical map nc Tree new root col
This problem should not use DFS to solve it, I have tried, but failed with this test case: [3,9,8,4,0,1,7,null,null,null,2,5]
My output is: [[4],[9,5],[3,0,1],[2,8],[7]]
But it was expected: [[4],[9,5],[3,0,1],[8,2],[7]]
Because the problem's request is: ...return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column)
private Map<Integer, List<Integer>> map = new HashMap<>(); public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); helper(root, 0); List<Integer> keys = new ArrayList<>(); for(int i:map.keySet()){ keys.add(i); } Collections.sort(keys); for(int i: keys){ res.add(map.get(i)); } return res; } private void helper(TreeNode root, int level){ if(root==null) return; map.putIfAbsent(level, new ArrayList<>()); map.get(level).add(root.val); helper(root.left, level-1); helper(root.right, level+1); }
The following is my BFS solution:
1. I used an object NodeCol to store both TreeNode and it's column. You can use two Queues too.
2. I sorted the Map's key to get the column from small to big. You can maintain a min and max to store minimal column and maximal column too.
class Solution { class NodeCol{ public TreeNode node; public int col; public NodeCol(TreeNode node, int col){ this.node = node; this.col = col; } } private Map<Integer, List<Integer>> map = new HashMap<>(); public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root==null) return res; Queue<NodeCol> queue = new LinkedList<>(); queue.offer(new NodeCol(root, 0)); while(!queue.isEmpty()){ NodeCol nc = queue.poll(); map.putIfAbsent(nc.col, new ArrayList<>()); map.get(nc.col).add(nc.node.val); if(nc.node.left!=null) queue.offer(new NodeCol(nc.node.left, nc.col-1)); if(nc.node.right!=null) queue.offer(new NodeCol(nc.node.right, nc.col+1)); } List<Integer> keys = new ArrayList<>(); for(int i:map.keySet()){ keys.add(i); } Collections.sort(keys); for(int i: keys){ res.add(map.get(i)); } return res; } }
标签:node,Binary,Vertical,map,nc,Tree,new,root,col 来源: https://www.cnblogs.com/feiflytech/p/15863848.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。