当前位置:首页 > 公司荣誉 >

Python:序列化二叉树

编辑:北京聚贤贵都宾馆有限公司时间:2017-09-10 09:53:26阅读次数:2
Python:序列化二叉树

Python:序列化二叉树。

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = 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, s): # write code here s1, i = s.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

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:十堰SEO http://shiyan.raoyu.net

上一篇:.NET中那些所谓的新语法之三:系统预定义委托与Lambda 下一篇:最后一页

相关阅读