smj007

Untitled

Jun 20th, 2022
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 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.  
  8. class Solution:
  9.     def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
  10.  
  11.         res = []
  12.        
  13.         q = collections.deque()
  14.        
  15.         # add the root to the queue as the base case
  16.         if root: q.append(root)
  17.  
  18.         # run outer loop till no elements left
  19.         # ensures been through all levels
  20.         while q:
  21.             # num elements at a single level
  22.             qLen = len(q)
  23.             level = []
  24.            
  25.             # iterate over elements of a single level in one pass
  26.             for i in range(qLen):
  27.                
  28.                 # pop the FIFO element of the queue and append to the result of level
  29.                 node = q.popleft()
  30.                 level.append(node.val)
  31.                    
  32.                 # add to the queue only if there is a child node
  33.                 if node.left:
  34.                     q.append(node.left)
  35.                  
  36.                 # add to the queue only if there is a child node
  37.                 if node.right:
  38.                     q.append(node.right)
  39.            
  40.             # append results of the single level
  41.             res.append(level)
  42.            
  43.         return res
  44.                    
  45.          
Advertisement
Add Comment
Please, Sign In to add comment