Skip to content

Latest commit

 

History

History
133 lines (111 loc) · 4.06 KB

File metadata and controls

133 lines (111 loc) · 4.06 KB

中文文档

Description

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., 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.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]

Example 2:

Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]

Example 3:

Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
Output: [[4],[9,5],[3,0,1],[8,2],[7]]

Example 4:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Solutions

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);
            offsetVals.computeIfAbsent(offset, k -> new ArrayList<>()).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());
    }
}

...