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] ]
1 public class Solution { 2 public List<List<Integer>> verticalOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if (root == null) { 5 return res; 6 } 7 //map‘s key is column, we assume the root column is zero, the left node will minus 1 ,and the right node will plus 1 8 HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); 9 Queue<TreeNode> queue = new LinkedList<>(); 10 //use a HashMap to store the TreeNode and the according cloumn value 11 HashMap<TreeNode, Integer> weight = new HashMap<TreeNode, Integer>(); 12 queue.offer(root); 13 weight.put(root, 0); 14 int min = 0; 15 while (!queue.isEmpty()) { 16 TreeNode node = queue.poll(); 17 int w = weight.get(node); 18 if (!map.containsKey(w)) { 19 map.put(w, new ArrayList<>()); 20 } 21 map.get(w).add(node.val); 22 if (node.left != null) { 23 queue.add(node.left); 24 weight.put(node.left, w - 1); 25 } 26 if (node.right != null) { 27 queue.add(node.right); 28 weight.put(node.right, w + 1); 29 } 30 //update min ,min means the minimum column value, which is the left most node 31 min = Math.min(min, w); 32 } 33 while (map.containsKey(min)) { 34 res.add(map.get(min++)); 35 } 36 return res; 37 } 38 }
reference:https://leetcode.com/discuss/73113/using-hashmap-bfs-java-solution
时间: 2024-12-13 09:07:01