題目連接: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); } } } }