_ Wins the binary sequence binary tree offer_

Binary Serialization

Title Description
Please implement two functions are used to serialize and deserialize binary

It refers to a sequence of binary: the binary tree is saved in a format string in accordance with the result of a traversing manner such that the memory can be set up binary persisted. Serialization may be based on the first order, in sequence, after, the binary tree traversal sequence is modified, the sequence of the result is a string representing the blank nodes (#) by some sequences of symbol to! End node represents a value (value!).

Deserialized binary tree means: The serialized string str some results obtained traversal order to reconstruct a binary tree.

This question will not be, directly on the reference answer it.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Serialize(self, root):
        # write code here
        if not root:
            return "#"
        return str(root.val) + "," + self.Serialize(root.left) + "," + self.Serialize(root.right)
    
    def Deserialize(self, s):
        # write code here
        list = s.split(",")
        return self.deserializeTree(list)
    
    def deserializeTree(self,list):
        if len(list)<=0:
            return None
        val = list.pop(0)
        root = None
        if val != "#":
            root = TreeNode(int(val))
            root.left = self.deserializeTree(list)
            root.right = self.deserializeTree(list)
        return root
Published 31 original articles · won praise 0 · Views 710

Guess you like

Origin blog.csdn.net/freedomUSTB/article/details/105210318