Leetcode 297 Serialize and Deserialize Binary Tree
Soru
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Bir binary tree’yi string’e çeviren (serialize) ve bu string’den tekrar aynı binary tree’yi oluşturan (deserialize) iki fonksiyonu implement etmen isteniyor.
Tree yapısını koruyarak, kayıpsız bir şekilde bu dönüşümleri yapmak gerekiyor.
Örneğin, ağaçtaki null değerler (yani çocukları olmayan dallar) da string temsilinde yer almalı.
Code
classCodec:defserialize(self,root):ifnotroot:return""#Eğer ağacımız boşsa (yani root yoksa), boş bir string döndürürüz.res=[]queue=deque([root])#Sonuçları tutmak için res listesi, BFS yapmak için de queue (bir deque) başlatıyoruz.whilequeue:node=queue.popleft()ifnode:res.append(str(node.val))queue.append(node.left)queue.append(node.right)else:res.append("null")#Kuyruktan bir düğüm alıyoruz.#Eğer düğüm varsa:#Değerini listeye ekliyoruz.#Sol ve sağ çocuklarını kuyruğa ekliyoruz.#Eğer düğüm None ise "null" olarak işaretliyoruz.#Bu şekilde tüm ağaç katman katman (level by level) taranıyor.return",".join(res)#Son olarak, listeyi virgülle birleştirerek string'e çeviriyoruz.defdeserialize(self,data):ifnotdata:returnNone#Eğer data boşsa, ağacımız da boştur, direkt None döneriz.nodes=data.split(",")root=TreeNode(int(nodes[0]))queue=deque([root])i=1#data string’ini ayırıp bir listeye çeviriyoruz.#İlk değer kök düğümdür.#BFS yapmak için bir kuyruk başlatıyoruz.#i pointer’ı, nodes listesinde ilerlemeyi sağlar.whilequeue:node=queue.popleft()ifnodes[i]!="null":node.left=TreeNode(int(nodes[i]))queue.append(node.left)i+=1ifnodes[i]!="null":node.right=TreeNode(int(nodes[i]))queue.append(node.right)i+=1#Kuyruktan bir düğüm alıp, sol ve sağ çocuklarını oluşturuyoruz (eğer "null" değilse).#Her oluşturulan çocuğu tekrar kuyruğa ekliyoruz ki onun da alt çocuklarını kurabilelim.returnroot