314 Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal

1. Question

Given a binary tree, return thevertical ordertraversal 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:

  1. 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]
    ]
  2. Given binary tree[3,9,8,4,0,1,7],

         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7

    return its vertical order traversal as:

    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]
  3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5](0's right child is 2 and 1's left child is 5),

         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
        /\
       /  \
       5   2

    return its vertical order traversal as:

    [
      [4],
      [9,5],
      [3,0,1],
      [8,2],
      [7]
    ]

2. Implementation

(1) BFS + HasMap

class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        if (root == null) return res;

        Map<Integer, List<Integer>> map = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> distance = new LinkedList<>();

        int min = 0, max = 0;
        queue.add(root);
        distance.add(0);

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();
                int curDistance = distance.remove();

                if (!map.containsKey(curDistance)) {
                    map.put(curDistance, new ArrayList<>());
                }
                map.get(curDistance).add(curNode.val);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                    distance.add(curDistance - 1);
                    min = Math.min(min, curDistance - 1);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                    distance.add(curDistance + 1);
                    max = Math.max(max, curDistance + 1);
                }
            }
        }

        for (int i = min; i <= max; i++) {
            res.add(map.get(i));
        }
        return res;
    }
}

3. Time & Space Complexity

BFS + HashMap: 时间复杂度: O(n), 空间复杂度: O(n)

Last updated