LeetCode solutions

1029. Vertical Order Traversal of a Binary Tree

My accepted Python solution to LeetCode problem 1029, Vertical Order Traversal of a Binary Tree, running in 0ms.

  • Difficulty: Hard
  • Python
  • Runtime 0ms
  • Memory 17.7MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.7MB, accepted 2026-01-01.

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]]:
        from collections import defaultdict
        
        # Store nodes as (col, row, val)
        nodes = []
        
        def dfs(node, row, col):
            if not node:
                return
            nodes.append((col, row, node.val))
            dfs(node.left, row + 1, col - 1)
            dfs(node.right, row + 1, col + 1)
        
        dfs(root, 0, 0)
        
        # Sort by col, then row, then value
        nodes.sort()
        
        # Group by column
        result = []
        current_col = None
        current_list = []
        
        for col, row, val in nodes:
            if col != current_col:
                if current_list:
                    result.append(current_list)
                current_list = [val]
                current_col = col
            else:
                current_list.append(val)
        
        if current_list:
            result.append(current_list)
        
        return result

Source