Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- step1: We will traverse the tree levelwise using BFS in serialize function and store in string.
- while stroing tree in string,we will give one space between every node and "null" for NULL node.
- step2: In deserialize function,we will store the nodes into vector of string and pass to fun.
- fun will traverse the tree levelwise using BFS and push the elements into tree.
- '''
- from collections import deque
- class Codec:
- def __init__(self):
- self.i=0
- def get_next_num(self,data):
- cur=''
- while data[self.i]!=' ':
- cur+=data[self.i]
- self.i+=1
- self.i+=1
- if cur=='None':
- return None
- return int(cur)
- def serialize(self, root):
- if root==None:
- return ''
- ans=''
- ans+=(str(root.val)+' ')
- q=deque()
- q.append(root)
- while len(q)>0:
- k=len(q)
- for i in range(k):
- temp=q.popleft()
- if temp.left:
- ans+=(str(temp.left.val)+' ')
- q.append(temp.left)
- else:
- ans+='None '
- if temp.right:
- ans+=(str(temp.right.val)+' ')
- q.append(temp.right)
- else:
- ans+='None '
- return ans
- def deserialize(self, data):
- print(data)
- if data=='':
- return None
- x=self.get_next_num(data)
- root=TreeNode(x)
- q=deque()
- q.append(root)
- while len(q)>0:
- k=len(q)
- print("The k is : ",k)
- for i in range(k):
- temp=q.popleft()
- x=self.get_next_num(data)
- print(f"The temp values is: {temp.val} and x is {x}")
- if x!=None:
- temp.left=TreeNode(x)
- q.append(temp.left )
- x=self.get_next_num(data)
- print(f"The temp values is: {temp.val} and x is {x}")
- if x!=None:
- temp.right=TreeNode(x)
- q.append(temp.right)
- return root
Advertisement
Add Comment
Please, Sign In to add comment