Given the root
of a binary tree, return the vertical order traversal of its nodes' values.
For each node at position (row, col)
, its left and right children will be at positions (row + 1, col - 1)
and (row + 1, col + 1)
respectively. The root of the tree is 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 at the rightmost column. There may be multiple nodes in the same row and column. In such a case, sort these nodes by their values.
Return the vertical order traversal of the binary tree.
Example 1:
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.
Example 2:
Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 9 is in this column.
Column 0: Nodes 3, 0, and 1 are in this column.
Column 1: Only node 8 is in this column.
Column 2: Only node 7 is in this column.
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]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Nodes 9 and 5 are in this column in that order from top to bottom.
Column 0: Nodes 3, 0, and 1 are in this column.
Column 1: Nodes 8 and 2 are in this column.
Column 2: Only node 7 is in this column.
Constraints:
[0, 1000]
.-1000 <= Node.val <= 1000
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine each node in the tree is a building, and we want to organize them based on their street address (vertical position). The brute force way is like trying every possible street address for each building and checking if that arrangement makes sense. We explore all combinations, figuring out the street layout that matches what we see in the tree.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def binary_tree_vertical_order_traversal_brute_force(root):
if not root:
return []
nodes_with_column = []
minimum_column = 0
maximum_column = 0
def traverse_tree(node, column):
nonlocal minimum_column, maximum_column
if not node:
return
nodes_with_column.append((node, column))
minimum_column = min(minimum_column, column)
maximum_column = max(maximum_column, column)
traverse_tree(node.left, column - 1)
traverse_tree(node.right, column + 1)
traverse_tree(root, 0)
vertical_order = []
# Iterate through all possible columns
for column_number in range(minimum_column, maximum_column + 1):
current_column_nodes = []
# Find all nodes that belong to the current column
for node, node_column in nodes_with_column:
if node_column == column_number:
current_column_nodes.append(node.val)
# Store current column's list of nodes into result
if current_column_nodes:
vertical_order.append(current_column_nodes)
return vertical_order
To display a binary tree vertically, imagine each node having a horizontal position. The optimal strategy involves traversing the tree while keeping track of each node's horizontal offset, then grouping nodes by their offset to produce the vertical order.
Here's how the algorithm would work step-by-step:
from collections import deque
def vertical_order_traversal(root):
if not root:
return []
node_horizontal_positions = {}
queue = deque([(root, 0)])
while queue:
node, horizontal_position = queue.popleft()
# Store nodes based on their horizontal position.
if horizontal_position not in node_horizontal_positions:
node_horizontal_positions[horizontal_position] = []
node_horizontal_positions[horizontal_position].append(node.val)
if node.left:
queue.append((node.left, horizontal_position - 1))
if node.right:
queue.append((node.right, horizontal_position + 1))
# Sort the horizontal positions to traverse from left to right.
sorted_horizontal_positions = sorted(node_horizontal_positions.keys())
# Build the final vertical order traversal list.
vertical_order = []
for horizontal_position in sorted_horizontal_positions:
vertical_order.append(node_horizontal_positions[horizontal_position])
return vertical_order
Case | How to Handle |
---|---|
Null or empty tree | Return an empty list as there are no nodes to traverse. |
Tree with only a root node | Return a list containing a single sublist with the root's value. |
Skewed tree (left or right only) | The algorithm should correctly handle skewed trees by assigning appropriate column indices and traversing all nodes. |
Tree with duplicate values | The algorithm should handle duplicate values correctly by including them in their respective vertical orders. |
Large tree depth which can cause call stack overflow if using recursive approach | Use an iterative approach like level order traversal to avoid stack overflow for very deep trees. |
Integer overflow when calculating column indices (extreme left or right) | Use a wider data type (e.g., long) for column indices or re-center the indexing to avoid overflows. |
Tree with negative node values | The algorithm should correctly handle negative node values without any modification. |
Tree is perfectly balanced | Algorithm should handle balanced trees efficiently and correctly place each node in the appropriate vertical order. |