Binary Tree Vertical Order Traversal — LeetCode 314 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary TreeSorting
Problem
#314
Reading time
4 min

The problem

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).

Example

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

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 verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        def dfs(root, depth, offset):
            if root is None:
                return
            d[offset].append((depth, root.val))
            dfs(root.left, depth + 1, offset - 1)
            dfs(root.right, depth + 1, offset + 1)

        d = defaultdict(list)
        dfs(root, 0, 0)
        ans = []
        for _, v in sorted(d.items()):
            v.sort(key=lambda x: x[0])
            ans.append([x[1] for x in v])
        return ans

Complexity

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

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 314. Binary Tree Vertical Order Traversal 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 314. Binary Tree Vertical Order Traversal?
LeetCode 314. Binary Tree Vertical Order Traversal is rated Medium on LeetCode.
What is the time complexity of LeetCode 314. Binary Tree Vertical Order Traversal?
The Python solution on this page runs in O(n\log \log n).
What is the space complexity of LeetCode 314. Binary Tree Vertical Order Traversal?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 314. Binary Tree Vertical Order Traversal cover?
LeetCode 314. Binary Tree Vertical Order Traversal is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree and Sorting on LeetCode.
Is LeetCode 314. Binary Tree Vertical Order Traversal a premium problem?
Yes. LeetCode 314. Binary Tree Vertical Order Traversal is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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