Vertical Order Traversal

Binary Trees FAQs Medium
  • The process of computing a binary tree's vertical order traversal is used in practical software development in data visualization and UI design
  • For example, organizational chart layouts and displaying hierarchical data, where nodes represent entities and edges represent relationships between entities, utilize this concept
  • Being able to depict this data in a visually digestible form, using a vertical traversal pattern, allows users to make more informed decisions based on these relationships
  • Efficient implementation of this problem is essential for ensuring the process is run effectively and quickly, enhancing the user experience

Compute the binary tree's vertical order traversal given its root.

The left and right children of a node at location (row, col) will be at (row + 1, col - 1) and (row + 1, col + 1), respectively. The tree's root is located at (0, 0).


The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the binary tree's vertical order traversal.

Examples:

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.

Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.

Column 1: Only node 20 is in this column.

Column 2: Only node 7 is in this column.

Input : root = [1, 2, 3, 4, 5, 6, 7]

Output : [ [4] , [2] , [1, 5, 6] , [3] , [7] ]

Explanation :

Column -2: Only node 4 is in this column.

Column -1: Only node 2 is in this column.

Column 0: Nodes 1, 5, and 6 are in this column.1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.

Column 1: Only node 3 is in this column.

Column 2: Only node 7 is in this column.

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Constraints

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

  • Use a dictionary (column_map) where the key is the column index and the value is a list of (row, value) tuples. Traverse the tree using BFS (queue-based approach) or DFS (recursion). At each node (row, col), store (row, value) in the column_map[col].
  • After traversal, extract values from column_map and sort them: Primary Sorting: By increasing column index (col). Secondary Sorting: Within each column, sort first by row and then by value (if the row is the same).

Company Tags

HashiCorp Zynga Alibaba Medtronic Walmart Deloitte NVIDIA Dropbox Uber Rockstar Games Epic Systems KPMG IBM Docker Optum McKinsey & Company Cloudflare AMD Wayfair Boston Consulting Group Red Hat Qualcomm Bain & Company Splunk Texas Instruments Google Microsoft Amazon Meta Apple Netflix Adobe