景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)

一种基于前序遍历的解法。


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

# 本解法是基于层次遍历的。序列化和反序列化中的队列中都会有None,但是循环时读到None时不会读它的左右节点。另外可以参考水中的鱼的前序遍历解法:
# http://fisherlei.blogspot.jp/2013/03/interview-serialize-and-de-serialize.html
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        if root is None:
            return ''

        list = []
        list.append(root)
        i = 0
        # 优化的层次遍历,不使用Queue,直接使用一个list存储和遍历。
        while i < len(list):
            if list[i] is not None:
                list.append(list[i].left)
                list.append(list[i].right)
            i += 1

        # 将list打印成逗号分隔的字符串
        res_str = ''
        for j in range(len(list)):
            if list[j] is not None:
                res_str += str(list[j].val) + ','
            else:
                res_str += 'x' + ','

        return res_str[0:-1]

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if data == '':
            return None

        input = data.split(',')

        root = TreeNode(input[0])
        q = Queue.Queue(-1)
        q.put(root)
        i = 0
        # 逻辑是使用队列循环节点,然后有一个计数器,如果节点不是'x',则计数器加2
        while q.qsize() > 0 and i + 2 < len(input):
            node = q.get()
            if node.val != 'x':
                i += 1
                left = TreeNode(input[i])
                if left.val != 'x':
                    node.left = left
                    q.put(left)
                i += 1
                right = TreeNode(input[i])
                if right.val != 'x':
                    right = TreeNode(input[i])
                    node.right = right
                q.put(right)

        return root


# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值