MediumNo. 0314LeetCode Premium
Binary Tree Vertical Order Traversal — LeetCode 314 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree, Sorting
- Reading time
- 4 min
- Source
- leetcode.com
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
# 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 ansComplexity
- Time
- O(nlog log n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
| 1261 | Find Elements in a Contaminated Binary Tree | Medium |
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(nlog 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.