题目连接:https://leetcode.com/problems...node
这道题要求vertical的order来保存结果,一开始想到的是用遍历的时候更新index,好比如今的index = 0,有左孩子的话就在最前面插入结果,且shift++。不过这样的话每一个subproblem的时间是O(N)了。
那么能够先用hashmap来cache,遍历的时候就要根据node所在的column的index来存,根节点的index从0开始,左边的孩子index-1,右边的孩子index+1,遍历树结束以后能够把全部index已经对应的值保存下来。还须要遍历hashmap从而获得要求的结果,由于hashmap没有order,因此还须要保存下index的最小值和最大值,从而知道hashmap遍历的范围。第一遍tree的遍历能够bfs也能够dfs。code
public class Solution { public List<List<Integer>> verticalOrder(TreeNode root) { // store the val according to their index in col map = new HashMap(); List<List<Integer>> result = new ArrayList(); if(root == null) return result; // traverse the tree bfs(root); // traverse map to get result for(int i = low; i <= high; i++) { if(map.containsKey(i)) { result.add(map.get(i)); } } return result; } Map<Integer, List<Integer>> map; int low = 0, high = 0; private void bfs(TreeNode root) { // bfs, use queue Queue<TreeNode> q = new LinkedList(); Queue<Integer> index = new LinkedList(); q.offer(root); index.offer(0); while(!q.isEmpty()) { TreeNode cur = q.poll(); int curIndex = index.poll(); // add node according to the column index if(!map.containsKey(curIndex)) map.put(curIndex, new ArrayList()); map.get(curIndex).add(cur.val); // update lowest index and highes index low = Math.min(low, curIndex); high = Math.max(high, curIndex); if(cur.left != null) { q.offer(cur.left); index.offer(curIndex - 1); } if(cur.right != null) { q.offer(cur.right); index.offer(curIndex + 1); } } } }