nathanwailes

LeetCode 314 - Binary Tree Vertical Order Traversal - 2024.03.09 solution

Mar 9th, 2024
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.     def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
  9.         # handle the case where the input is empty
  10.         if not root: return []
  11.  
  12.         # create some intermediate data structures / variables that will let us generate the answer
  13.         level_order_traversal = []  # node and col_offset
  14.         min_col_offset = 0
  15.         max_col_offset = 0
  16.  
  17.         # populate the intermediate data structures / variables
  18.         queue = [[root, 0]]
  19.         while queue:
  20.             current_node, col_offset = queue.pop(0)
  21.  
  22.             # update our intermediate data structures / variables
  23.             level_order_traversal.append([current_node, col_offset])
  24.             min_col_offset = min(min_col_offset, col_offset)
  25.             max_col_offset = max(max_col_offset, col_offset)
  26.  
  27.             # add children to the queue
  28.             if current_node.left:
  29.                 queue.append([current_node.left, col_offset - 1])
  30.             if current_node.right:
  31.                 queue.append([current_node.right, col_offset + 1])
  32.  
  33.         # use the intermediate data structures/variables to generate the answer
  34.         number_of_cols = max_col_offset - min_col_offset + 1
  35.         output_list = [[] for _ in range(number_of_cols)]
  36.         level_order_traversal.reverse()
  37.         while level_order_traversal:
  38.             current_node, offset = level_order_traversal.pop()
  39.             column = offset - min_col_offset
  40.             output_list[column].append(current_node.val)
  41.        
  42.         return output_list
  43.  
Advertisement
Add Comment
Please, Sign In to add comment