Share my Java BFS solution


  • 0
    N
    public class Solution {
        public List<List<Integer>> verticalOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) return result;
            Map<Integer, List<Integer>> map = new HashMap<>();
            Queue<TreeNode> queue = new LinkedList<>();
            Queue<Integer> columns = new LinkedList<>();
            queue.offer(root);
            columns.offer(0);
            int lowestColumn = 0;
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                int col = columns.poll();
                if (map.containsKey(col)) {
                    map.get(col).add(node.val);
                } else {
                    List<Integer> vals = new ArrayList<>();
                    vals.add(node.val);
                    map.put(col, vals);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                    columns.offer(col-1);
                    lowestColumn = Math.min(lowestColumn, col - 1);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    columns.offer(col+1);
                }
            }
            while (map.containsKey(lowestColumn)) {
                result.add(map.get(lowestColumn));
                map.remove(lowestColumn);
                lowestColumn++;
            }
            return result;
        }
    }
    

Log in to reply
 

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