imashutosh51

Serialize and Deserialize Binary Tree

Oct 25th, 2022 (edited)
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.22 KB | None | 0 0
  1. '''
  2. Logic:
  3. step1: We will traverse the tree levelwise using BFS in serialize function and store in string.
  4. while stroing tree in string,we will give one space between every node and "null" for NULL node.
  5.  
  6. step2: In deserialize function,we will store the nodes into vector of string and pass to fun.
  7. fun will traverse the tree levelwise using BFS and push the elements into tree.
  8. '''
  9.  
  10. from collections import deque
  11. class Codec:
  12.     def __init__(self):
  13.         self.i=0
  14.     def get_next_num(self,data):
  15.         cur=''
  16.         while data[self.i]!=' ':
  17.             cur+=data[self.i]
  18.             self.i+=1
  19.         self.i+=1
  20.         if cur=='None':
  21.             return None
  22.         return int(cur)
  23.  
  24.     def serialize(self, root):
  25.         if root==None:
  26.             return ''
  27.         ans=''
  28.         ans+=(str(root.val)+' ')
  29.         q=deque()
  30.         q.append(root)
  31.         while len(q)>0:
  32.             k=len(q)
  33.             for i in range(k):
  34.                 temp=q.popleft()
  35.                 if temp.left:
  36.                     ans+=(str(temp.left.val)+' ')
  37.                     q.append(temp.left)
  38.                 else:
  39.                     ans+='None '
  40.                
  41.                 if temp.right:
  42.                     ans+=(str(temp.right.val)+' ')
  43.                     q.append(temp.right)
  44.                 else:
  45.                     ans+='None '
  46.         return ans
  47.  
  48.        
  49.  
  50.     def deserialize(self, data):
  51.         print(data)
  52.         if data=='':
  53.             return None
  54.         x=self.get_next_num(data)
  55.         root=TreeNode(x)
  56.         q=deque()
  57.         q.append(root)
  58.         while len(q)>0:
  59.             k=len(q)
  60.             print("The k is : ",k)
  61.             for i in range(k):
  62.                 temp=q.popleft()
  63.                 x=self.get_next_num(data)
  64.                 print(f"The temp values is: {temp.val} and x is {x}")
  65.                 if x!=None:
  66.                     temp.left=TreeNode(x)
  67.                     q.append(temp.left )
  68.  
  69.                 x=self.get_next_num(data)
  70.                 print(f"The temp values is: {temp.val} and x is {x}")
  71.                 if x!=None:
  72.                     temp.right=TreeNode(x)
  73.                     q.append(temp.right)
  74.                    
  75.         return root
Advertisement
Add Comment
Please, Sign In to add comment