Java BFS concise code using 2 maps


  • 0
    public class Solution {
        public List<List<Integer>> verticalOrder(TreeNode root) {
            if (root == null) 
                return new ArrayList<>();
            Map<TreeNode, Integer> columnMap = new HashMap<>();
            Map<Integer, List<Integer>> vertical = new TreeMap<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            columnMap.put(root, 0);
            int col;
            while (!queue.isEmpty()) {
                root = queue.poll();
                col = columnMap.get(root);
                if (!vertical.containsKey(col)) {
                    vertical.put(col, new ArrayList<>());
                }
                vertical.get(col).add(root.val);
                if (root.left != null) {
                    columnMap.put(root.left, col - 1);
                    queue.offer(root.left);
                }
                if (root.right != null) {
                    columnMap.put(root.right, col + 1);
                    queue.offer(root.right);
                }
            }
            return new ArrayList<>(vertical.values());
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.