1. 程式人生 > >[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary Tree

[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary Tree

one traversal class scrip result elf www urn roo

7. Serialize and Deserialize Binary Tree/297. Serialize and Deserialize Binary Tree

  • 本題難度: Medium/Hard
  • Topic: Binary Tree

Description

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization‘ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization‘.

Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

3
/ 9 20
/ 15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

Notice
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won‘t check the result of serialize.

別人的代碼

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
        
    def serialize(self, root):
        def doit(node):
            if node:
                vals.append(str(node.val))
                doit(node.left)
                doit(node.right)
            else:
                vals.append(‘#‘)
        vals = []
        doit(root)
        return ‘ ‘.join(vals)

    def deserialize(self, data):
        def doit():
            val = next(vals)
            if val == ‘#‘:
                return None
            node = TreeNode(int(val))
            node.left = doit()
            node.right = doit()
            return node
        vals = iter(data.split())
        return doit()

思路
使用深度優先遍歷,但是要註意占位。

  • 時間復雜度
  • 出錯

[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary Tree