題目:
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its vertical order traversal as:
[ [9], [3,15], [20], [7] ]
Given binary tree [3,9,20,4,5,2,7],
_3_ / \ 9 20 / \ / \ 4 5 2 7
return its vertical order traversal as:
[ [4], [9], [3,5,2], [20], [7] ]
鏈接: http://leetcode.com/problems/binary-tree-vertical-order-traversal/
題解:
二叉樹Vertical order traversal。這道題意思很簡單但例子舉得不夠好,假如上面第二個例子里5還有右子樹的話,就會和20在一條column里。總的來說就是假定一個node的column是 i,那么它的左子樹column就是i - 1,右子樹column就是i + 1。我們可以用decorator模式建立一個TreeColumnNode,包含一個TreeNode,以及一個column value,然后用level order traversal進行計算就可以了,計算的時候用一個HashMap保存column value以及相同value的點。也要設置一個min column value和一個max column value,方便最后按照從小到大順序獲取hashmap里的值輸出。這道題Discuss區Yavinci大神寫得非常棒,放在reference里。
Time Complexity - O(n), Space Complexity - O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private class TreeColumnNode{ public TreeNode treeNode; int col; public TreeColumnNode(TreeNode node, int col) { this.treeNode = node; this.col = col; } } public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null) { return res; } Queue<TreeColumnNode> queue = new LinkedList<>(); Map<Integer, List<Integer>> map = new HashMap<>(); queue.offer(new TreeColumnNode(root, 0)); int curLevel = 1; int nextLevel = 0; int min = 0; int max = 0; while(!queue.isEmpty()) { TreeColumnNode node = queue.poll(); if(map.containsKey(node.col)) { map.get(node.col).add(node.treeNode.val); } else { map.put(node.col, new ArrayList<Integer>(Arrays.asList(node.treeNode.val))); } curLevel--; if(node.treeNode.left != null) { queue.offer(new TreeColumnNode(node.treeNode.left, node.col - 1)); nextLevel++; min = Math.min(node.col - 1, min); } if(node.treeNode.right != null) { queue.offer(new TreeColumnNode(node.treeNode.right, node.col + 1)); nextLevel++; max = Math.max(node.col + 1, max); } if(curLevel == 0) { curLevel = nextLevel; nextLevel = 0; } } for(int i = min; i <= max; i++) { res.add(map.get(i)); } return res; } }
Reference:
https://leetcode.com/discuss/75054/5ms-java-clean-solution
https://leetcode.com/discuss/73113/using-hashmap-bfs-java-solution
https://leetcode.com/discuss/74022/hashmap-bfs-solution-in-java
https://leetcode.com/discuss/73893/java-level-order-traversal-solution
http://algorithms.tutorialhorizon.com/print-the-binary-tree-in-vertical-order-path/
http://www.geeksforgeeks.org/print-binary-tree-vertical-order/
http://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
