Vertical Order Traversal of a Binary Tree — LeetCode 987 Python Solution

HardTreeDepth-First SearchBreadth-First SearchHash TableBinary TreeSorting
Problem
#987
Reading time
5 min

The problem

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.

Example

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.

Python solution

Python
# 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 verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
        def dfs(root: Optional[TreeNode], i: int, j: int):
            if root is None:
                return
            nodes.append((j, i, root.val))
            dfs(root.left, i + 1, j - 1)
            dfs(root.right, i + 1, j + 1)

        nodes = []
        dfs(root, 0, 0)
        nodes.sort()
        ans = []
        prev = -2000
        for j, _, val in nodes:
            if prev != j:
                ans.append([])
                prev = j
            ans[-1].append(val)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 987. Vertical Order Traversal of a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 987. Vertical Order Traversal of a Binary Tree?
LeetCode 987. Vertical Order Traversal of a Binary Tree is rated Hard on LeetCode.
What is the time complexity of LeetCode 987. Vertical Order Traversal of a Binary Tree?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 987. Vertical Order Traversal of a Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 987. Vertical Order Traversal of a Binary Tree cover?
LeetCode 987. Vertical Order Traversal of a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview