Advertisement
smj007

Binary Tree Vertical Order Transveral

Jul 30th, 2024
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. class Solution:
  2.     def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
  3.         if not root:
  4.                 return []
  5.  
  6.         from collections import defaultdict, deque
  7.         q = deque()
  8.         q.append((root, 0, 0))
  9.         hashmap = defaultdict(list)
  10.         min_col = float("inf")
  11.         max_col = -float("inf")
  12.  
  13.         while q:
  14.             node, col, level = q.popleft()
  15.             if node:  # check if the node is not None
  16.                 if col < min_col:
  17.                     min_col = col
  18.                 if col > max_col:
  19.                     max_col = col
  20.                 hashmap[col].append(node.val)
  21.                 q.append((node.left, col - 1, level + 1))
  22.                 q.append((node.right, col + 1, level + 1))
  23.  
  24.         return [hashmap[col] for col in range(min_col, max_col + 1)]
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement