您的位置:首页 > 编程语言 > Python开发

Python3实现二叉树的序列化和反序列化

2018-11-16 17:41 423 查看

Python3实现二叉树的序列化和反序列化

python

# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: P♂boy
@License: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@Contact: 17647361832@163.com
@Software: Pycharm
@File: Tr.py
@Time: 2018/11/16 11:36
@Desc:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None

class Solution:
def serialize(self, root):
# write code here
tree, ch = [root], []
while len(tree) > 0:
temp = tree.pop(0)
if temp is None:
ch.append('# ')
else:
ch.append(str(temp.val) + ' ')
tree.append(temp.left)
tree.append(temp.right)
return ''.join(ch)

def deserialize(self, data):
# write code here
s1, i = data.split(), 0     # 用空格作为分隔符
if s1[i] == '#':
return None
root = TreeNode(int(s1[i]))
tree = [root]
while len(tree) > 0:
te = tree.pop(0)
i += 1
if s1[i] != '#':
k = TreeNode(int(s1[i]))
te.left = k
tree.append(k)
i += 1
if s1[i] != '#':
k = TreeNode(int(s1[i]))
te.right = k
tree.append(k)
return root

T = TreeNode(8)
T.left = TreeNode(9)
T.right = TreeNode(10)
T.left.left = TreeNode(20)
T.left.right = TreeNode(20)
print(Solution().serialize(T))
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: