python level visit of the tree beats 97.99%


  • 0
    class Codec:
        #NULL=99999#if a node is None ,we assign this node.val=99999 
        def serialize(self, root):
            """Encodes a tree to a single string.
            :type root: TreeNode
            :rtype: str
            """
            if root==None:
                return str([])
            stack=collections.deque()
            stack.append(root)
            res=[]
            while len(stack)>0:
                node=stack.popleft()
                if node!=None:
                    L,R=node.left,node.right
                    res.append(node.val)
                    stack.append(L)
                    stack.append(R)
                else:
                    res.append(99999)
    
            while res[-1]==99999:
                res.pop()
            return str(res)
    
        def deserialize(self, data):
            """Decodes your encoded data to tree.
            
            :type data: str
            :rtype: TreeNode
            """
            nodeL=data.replace('[','').replace(']','').split(',')
            if len(nodeL)==0 or nodeL==[''] or nodeL==[]:
                return None
            nodeL=[ int(i) for i in nodeL ]
            i,L=0,len(nodeL)
            resL=[]
            p=root=TreeNode(nodeL[0])
            resL.append(p)
            j=1
            while i<len(resL):
                p=resL[i]
                if j<L and p:
                    p.left=TreeNode(nodeL[j]) if nodeL[j]!=99999 else None
                    resL.append(p.left)
                    j+=1
                if j<L and p:
                    p.right=TreeNode(nodeL[j]) if nodeL[j]!=99999 else None
                    resL.append(p.right)
                    j+=1
                i+=1
            
            return root
    

  • 0
    S

    Passing test cases and running fast does not mean good solution. What if there is a node whose value is 99999? You can easily fix this.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.