Skip to content

Latest commit

 

History

History
148 lines (119 loc) · 4.29 KB

File metadata and controls

148 lines (119 loc) · 4.29 KB

English Version

题目描述

给你一个二叉树的根结点,返回其结点按 垂直方向(从上到下,逐列)遍历的结果。

如果两个结点在同一行和列,那么顺序则为 从左到右

 

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[9],[3,15],[20],[7]]

示例 2:

输入:root = [3,9,8,4,0,1,7]
输出:[[4],[9],[3,0,1],[8],[7]]

示例 3:

输入:root = [3,9,8,4,0,1,7,null,null,null,2,5]
输出:[[4],[9,5],[3,0,1],[8,2],[7]]

示例 4:

输入:root = []
输出:[]

 

提示:

  • 树中结点的数目在范围 [0, 100]
  • -100 <= Node.val <= 100

解法

“BFS 层次遍历”实现。

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def verticalOrder(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return []
        q = collections.deque([(root, 0)])
        offset_vals = collections.defaultdict(list)
        while q:
            node, offset = q.popleft()
            offset_vals[offset].append(node.val)
            if node.left:
                q.append((node.left, offset - 1))
            if node.right:
                q.append((node.right, offset + 1))
        res = []
        for _, vals in sorted(offset_vals.items(), key=lambda x: x[0]):
            res.append(vals)
        return res

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>> verticalOrder(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        Map<Integer, List<Integer>> offsetVals = new TreeMap<>();
        Map<TreeNode, Integer> nodeOffsets = new HashMap<>();
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        nodeOffsets.put(root, 0);

        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            int offset = nodeOffsets.get(node);
            if (!offsetVals.containsKey(offset)) {
                offsetVals.put(offset, new ArrayList<>());
            }
            offsetVals.get(offset).add(node.val);
            if (node.left != null) {
                q.offer(node.left);
                nodeOffsets.put(node.left, offset - 1);
            }
            if (node.right != null) {
                q.offer(node.right);
                nodeOffsets.put(node.right, offset + 1);
            }
        }
        return new ArrayList<>(offsetVals.values());
    }
}

...