题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
感觉写了一座💩💩💩💩屎山💩💩💩💩,供大家观摩留念。。。
代码核心思想是BFS遍历,使用{}作为不同节点的分割(节点可能出现10这样的两个字符的数据。) 然后一堆判断。 咦。。。好恶心🤮🤮🤮🤮🤮
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
if root == None:
return ""
stack = [root]
valstr = ""
while stack != None and len(stack) !=0:
c = stack.pop(0)
if c.val == -1:
valstr += "{#}"
continue
else:
valstr += '{'+str(c.val)+'}'
if c.left != None:
stack.append(c.left)
if c.left == None:
stack.append(TreeNode(-1))
if c.right != None:
stack.append(c.right)
if c.right == None:
stack.append(TreeNode(-1))
return valstr
def Deserialize(self, s):
if s == "":
return None
tmpstr = ""
i = 0
while i < len(s[1:]) and s[i] != '}':
i +=1
tmpstr = s[1:i]
startindex = len(tmpstr) +2
pp = TreeNode(int(tmpstr))
pc = pp
step = 0
stack = [pc]
p = None
tmpstr = ""
i = startindex
while i < len(s):
if s[i] == '{':
stridx = i
while i < len(s[1:]) and s[i] != '}':
i +=1
tmpstr = s[stridx+1:i]
i +=1
if tmpstr == "#":
if (step) % 2 == 1:
stack.pop(0)
step +=1
continue
p = stack[0]
if (step) % 2 == 0:
p.left = TreeNode(int(tmpstr))
stack.append(p.left)
else:
stack.pop(0)
p.right = TreeNode(int(tmpstr))
stack.append(p.right)
step +=1
return pp