Advertisement
uopspop

Untitled

Jan 26th, 2022
916
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import queue
  2.  
  3. class BT_Array_BFS:
  4.     def __init__(self, nums):
  5.         self.__nums = nums
  6.  
  7.     def traverse_levelorder_bfs(self):
  8.         if len(self.__nums) == 0:
  9.             return
  10.  
  11.         q = queue.Queue()
  12.  
  13.         # initialzation
  14.         i_root = 0
  15.         q.put(i_root)
  16.  
  17.         while True:
  18.             if q.qsize() == 0:
  19.                 break
  20.  
  21.             i = q.get()
  22.             if i >= len(self.__nums):
  23.                 continue
  24.             if self.__nums[i] == None:
  25.                 continue
  26.  
  27.             print(self.__nums[i], end = " ")
  28.  
  29.             i_left = (i+1) * 2 - 1
  30.             i_right = (i+1) * 2
  31.  
  32.             q.put(i_left)
  33.             q.put(i_right)
  34.  
  35.  
  36. if __name__ == '__main__':
  37.     nums = [
  38.         5,
  39.         2, 6,
  40.         1, 4, None, 7,
  41.         None, None, 3, None, None, None, None, None]
  42.     bt = BT_Array_BFS(nums)
  43.     print()
  44.  
  45.     print("\nlevel-order:", end = " ")
  46.     bt.traverse_levelorder_bfs()
  47.     print()
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement