剣を指すオファー34 ~ 37题python補充学習記録

问题35:複雑な鎖表のコピー

自分の思ったようには全部で2回の遍暦、

  • 初めて遍暦に新たな鎖表を作り出すか、next関係を構築するとともに、新旧の鎖表ノードごとにそれぞれのリストに入れ(目
  • 2回目の遍暦は利用list.index関数下标を见つけて、その対応に

ではないかもしれないが最も优解も、自分が出たいの、励まして👏

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head==None:
            return None
        newhead=Node(head.val)
        old,new=head,newhead
        oldlist,newlist=[],[]
        while old!=None:
            oldlist.append(old)
            newlist.append(new)
            if old.next!=None:
                tmp=Node(old.next.val)
                new.next=tmp
            else:
                new.next=None
            old,new=old.next,new.next
        old,new=head,newhead
        while old!=None:
            if old.random!=None:
                ind=oldlist.index(old.random)
                new.random=newlist[ind]
            else:
                new.random=None
            old,new=old.next,new.next
        return newhead

问题37:序列2分木

序列化もいいし、利用すれば列、反序列化は初めてだが、本を二分木の性格(たい第ノードの左がノード2 i処に、

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if root==None:
            return '[]'
        queue,res=[root],'['
        while len(queue)!=0:
            tmp=queue.pop(0)
            if tmp!=None:
                res+=str(tmp.val)+','
                queue.append(tmp.left)
                queue.append(tmp.right)
            else:
                res+=('null,') 
        res=res[:-1]+']'
        return res


    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if data=='[]':
            return None
        data=data[1:-1].split(',')
        rt=TreeNode(int(data[0]))
        queue,ind=[rt],1
        while len(queue)!=0:
            root=queue.pop(0)
            if data[ind]!='null':
                root.left=TreeNode(int(data[ind]))
                queue.append(root.left)
            ind+=1
            if data[ind]!='null':
                root.right=TreeNode(int(data[ind]))
                queue.append(root.right)
            ind+=1
        return rt

        
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
ソースネットワーク 戻る