LeetCode 314. Binary Tree Vertical Order Traversal

Description

https://leetcode.com/problems/binary-tree-vertical-order-traversal/

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

If two nodes are in the same row and column, the order should be from left to right.

Example 1:

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

Example 2:

Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]

Example 3:

Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
Output: [[4],[9,5],[3,0,1],[8,2],[7]]

Example 4:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Explanation

Use breadth-first search with a column mapping. Each left node is attached to the current column – 1, each right node is attached to the current column + 1.

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]]:
        
        if not root:
            return []
        
        column_table = defaultdict(list)
                
        results = []
        queue = []
        queue.append((root, 0))
        
        while queue:
            node, column = queue.pop(0)            
            column_table[column].append(node.val)
            
            
            if node.left:
                queue.append((node.left, column - 1))
            
            if node.right:
                queue.append((node.right, column + 1))

        
        for column in sorted(column_table.keys()):
            results.append(column_table[column])
            
            
        return results
  • Time Complexity: O(N).
  • Space Complexity: O(N).

One Thought to “LeetCode 314. Binary Tree Vertical Order Traversal”

Leave a Reply

Your email address will not be published. Required fields are marked *