景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
来源:互联网 发布:最好的外汇交易软件 编辑:程序博客网 时间:2024/05/29 11:44
一种基于前序遍历的解法。
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneimport Queue# 本解法是基于层次遍历的。序列化和反序列化中的队列中都会有None,但是循环时读到None时不会读它的左右节点。另外可以参考水中的鱼的前序遍历解法:# http://fisherlei.blogspot.jp/2013/03/interview-serialize-and-de-serialize.htmlclass 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
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- [leetcode] 297. Serialize and Deserialize Binary Tree 解题报告
- [Leetcode] 297. Serialize and Deserialize Binary Tree 解题报告
- 【LeetCode】Serialize and Deserialize Binary Tree 解题报告
- [LeetCode]297. Serialize and Deserialize Binary Tree
- LeetCode 297. Serialize and Deserialize Binary Tree
- leetcode 297. Serialize and Deserialize Binary Tree
- LeetCode 297. Serialize and Deserialize Binary Tree
- Leetcode 297. Serialize and Deserialize Binary Tree
- LeetCode 297. Serialize and Deserialize Binary Tree
- [LeetCode]297. Serialize and Deserialize Binary Tree
- Leetcode 297. Serialize and Deserialize Binary Tree
- [leetcode]297. Serialize and Deserialize Binary Tree
- leetcode 297 : Serialize and Deserialize Binary Tree
- LeetCode Serialize and Deserialize Binary Tree
- [LeetCode] Serialize and Deserialize Binary Tree
- [LeetCode]Serialize and Deserialize Binary Tree
- LeetCode -- Serialize and Deserialize Binary Tree
- em算法
- 详细整合教程(Spring+SpringMVC+MyBatis)
- 使用selenium IDE开始简易自动化测试
- VirtualBox配置网络以及SSH登陆配置
- Android中属性动画和补间动画的区别
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- 如何在Ubuntu上几步搭建Git Server
- Lua string函数说明
- C#验证码的使用—两种实现
- 为setup.py添加c:c++ 头文件或者库的搜索路径
- HTML学习笔记——(三)HTML元素和属性
- CFormview无法去除滚动条原因
- YTU 2891: E--围栏
- 正则表达式