[LeetCode] 987. Vertical Order Traversal of a Binary Tree

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

Example 1:
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.

Example 2:
Example 2
Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.

Example 3:
Example 3
Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.

Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 1000

二叉树的垂序遍历。

给你二叉树的根结点 root ,请你设计算法计算二叉树的 垂序遍历 序列。
对位于 (row, col) 的每个结点而言,其左右子结点分别位于 (row + 1, col - 1) 和 (row + 1, col + 1) 。树的根结点位于 (0, 0) 。
二叉树的 垂序遍历 从最左边的列开始直到最右边的列结束,按列索引每一列上的所有结点,形成一个按出现位置从上到下排序的有序列表。如果同行同列上有多个结点,则按结点的值从小到大进行排序。
返回二叉树的 垂序遍历 序列。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/vertical-order-traversal-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题意跟 314 题非常像,但是 314 只要求我们找到横坐标一样的元素,把他们合成一组;但是这个题的题目描述写的非常不清楚,根据 test case,实际的要求是

  • 如果是正常情况,自然就是从左往右按 column 输出所有节点;在每个 column 中,节点按照自身到根节点的距离(深度)由近到远输出
  • 如果有两个节点的偏移量相同(应该是在同一个column里或一个是左孩子一个是右孩子),而且他们之于根节点的距离(深度)也相同,那么再按照 node.val 从小到大排序,比如例子二和离子三中的 5 就在 6 的前面

这里我提供一个 BFS 的做法,思路跟 314 题也很像。这里我还是需要用到两个 queue,一个存遍历的所有节点,一个存每个节点相对于根节点 root 的偏移量;我还需要一个总的 hashmap 记录不同偏移量分别都是哪些节点 和一个临时的 hashmap level 记录当前层不同偏移量分别都是哪些节点。

之后按 BFS 的思路遍历整棵树,首先我们需要记录每一层的节点个数 size,同时我们需要对同一层的节点进行一个局部的统计,用临时的 hashmap level 记录每一层的节点的偏移量和节点信息。当前层遍历完毕之后,对于这个 level,我们把所有的节点拿出来并排序,此时 level 里存的都是当前层的节点,把排序好的 list 再加入总的 hashmap 里。这个做法的巧妙之处在于我们先用 level map 存了同一层的节点并对同一偏移量的节点排好序,这样当我处理完当前层的时候,我把所有的节点先加入最后的结果集。这种做法就保证了最后结果集里,偏移量相同的节点,层数/深度小的节点在前。

复杂度

时间O(n) - 遍历了整棵树
空间O(n)

代码

Java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> verticalTraversal(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        // corner case
        if (root == null) {
            return res;
        }

        // normal case
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> dis = new LinkedList<>();
        int min = 0;
        int max = 0;
        queue.offer(root);
        dis.offer(0);
        while (!queue.isEmpty()) {
            int size = queue.size();
            // 统计同一层上不同偏移量都有哪些节点
            // <偏移量, List<Integer>>
            HashMap<Integer, List<Integer>> level = new HashMap<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                int col = dis.poll();
                if (!level.containsKey(col)) {
                    level.put(col, new ArrayList<>());
                }
                level.get(col).add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                    dis.offer(col - 1);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                    dis.offer(col + 1);
                }
                min = Math.min(min, col);
                max = Math.max(max, col);
            }

            // 把每一层上的节点加入最后的hashmap
            // 这样层数较低的节点会被优先加入最后的结果集
            for (int key : level.keySet()) {
                if (!map.containsKey(key)) {
                    map.put(key, new ArrayList<>());
                }
                List<Integer> list = level.get(key);
                Collections.sort(list);
                map.get(key).addAll(list);
            }
        }

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

相关题目

314. Binary Tree Vertical Order Traversal
987. Vertical Order Traversal of a Binary Tree
posted @ 2020-05-13 10:52  CNoodle  阅读(197)  评论(0编辑  收藏  举报