314. Binary Tree Vertical Order Traversal(树bfs)
bfs dfs
Last updated
bfs dfs
Last updated
from collections import defaultdict
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
# Dictionary to store nodes by column and row
column_map = defaultdict(list)
min_col = max_col = 0
def dfs(node, row, col):
nonlocal min_col, max_col
if not node:
return
column_map[col].append((row, node.val))
min_col = min(min_col, col)
max_col = max(max_col, col)
dfs(node.left, row + 1, col - 1)
dfs(node.right, row + 1, col + 1)
dfs(root, 0, 0)
# Sort each column's entries by row, then by insertion order
result = []
for col in range(min_col, max_col + 1):
# Sort by row to maintain top-to-bottom order
column_map[col].sort(key=lambda x: x[0])
# Extract just the values
result.append([val for (row, val) in column_map[col]])
return result # 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
from collections import deque
class Solution:
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
q = deque([(root, 0,0)])
cols = collections.defaultdict(list)
while q:
node, row, col = q.popleft()
cols[col].append((row,node.val))
if node.left:
q.append((node.left, row+1, col-1))
if node.right:
q.append((node.right, row+1, col+1))
res = []
for col in sorted(cols.keys()):
cols[col].sort()
res.append([v for r,v in cols[col]])
return res