Advertisement
jinhuang1102

102. Binary Tree Level Order Traversal

Jan 27th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.left = None
  6. #         self.right = None
  7. import collections
  8.  
  9. class Solution(object):
  10.     def levelOrder(self, root):
  11.         """
  12.        :type root: TreeNode
  13.        :rtype: List[List[int]]
  14.        """
  15.         if not root:
  16.             return []
  17.        
  18.         # queue FIFO
  19.         q = collections.deque()
  20.         q.append(root)              # q = [ TreeNode(3) ]
  21.        
  22.         res = []
  23.         while q:
  24.             num = len(q)
  25.             level = []
  26.             for _ in range(num):
  27.                 node = q.popleft()
  28.                 level.append(node.val)
  29.                
  30.                 if node.left:
  31.                     q.append(node.left)
  32.                 if node.right:
  33.                     q.append(node.right)
  34.                    
  35.             res.append(level)
  36.            
  37.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement