Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 987 · BFS / Level Order

Vertical Order Traversal of a Binary Tree

LeetCode 987 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Map column → row → sorted values.

ಕಠಿಣHash TableTreeDepth-First SearchBreadth-First SearchSorting
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Vertical Order Traversal of a Binary Tree (LeetCode 987) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — BFS / Level Order ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Give every node a column (left −1, right +1) and a row (depth). Group values by column, then by row, sorting values that share the same row and column. Output columns from left to right.

Approach

  1. 1

    BFS carrying (node, column, row).

  2. 2

    Insert node.val into map[column][row] and keep that list sorted.

  3. 3

    Sort columns; within a column rows are already in BFS order.

  4. 4

    Concatenate each column's lists.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

BFS + nested mapsPythonO(n log n) time
class Solution:
    def verticalTraversal(self, root):
        queue = [[root, 0, 0]]
        lineMap = {}
        res = []
        while queue:
            node, line, level = queue.pop(0)
            lineMap.setdefault(line, {})
            lineMap[line].setdefault(level, [])
            lineMap[line][level].append(node.val)
            lineMap[line][level].sort()
            if node.left:
                queue.append([node.left, line - 1, level + 1])
            if node.right:
                queue.append([node.right, line + 1, level + 1])
        for line in sorted(lineMap):
            res.append([])
            for level, values in lineMap[line].items():
                res[-1].extend(values)
        return res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Vertical Order Traversal of a Binary Tree — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Vertical Order Traversal of a Binary Tree ಹಿಂದಿನ intuition ಏನು?

Give every node a column (left −1, right +1) and a row (depth). Group values by column, then by row, sorting values that share the same row and column. Output columns from left to right.

Vertical Order Traversal of a Binary Tree (LeetCode 987) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. BFS carrying (node, column, row). 2. Insert node.val into map[column][row] and keep that list sorted. 3. Sort columns; within a column rows are already in BFS order. 4. Concatenate each column's lists.

Vertical Order Traversal of a Binary Tree ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log n). Space: O(n). (Accepted approach: BFS + nested maps.)

Vertical Order Traversal of a Binary Tree ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Ties at the same row and column are broken by value, not left/right.