leetcode之Serialize and Deserialize Binary Tree
来源:互联网 发布:数组大小可以任意改变 编辑:程序博客网 时间:2024/05/01 07:09
这题主要还是运用了广度搜索优先的方法。一层一层的遍历来获得每层的数据。然后依次安装上去。代码如下:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return '' stack1 = [root] list1 = [root.val] while len(stack1) != 0: stack2 = [] for i in stack1: if i: stack2.append(i.left) stack2.append(i.right) for i in stack2: if i: list1.append(i.val) else: list1.append(None) stack1 = stack2 if stack2 == []: return str(list1) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '': return None data = data[1:-1] data = data.split(', ') root = TreeNode(int(data[0])) data = data[1:][::-1] stack1 = [root] while data != []: stack2 = [] for i in stack1: if data[-1] == 'None': data.pop() i.left = None if data[-1] == 'None': data.pop() i.right = None else: i.right = TreeNode(int(data.pop())) stack2.append(i.right) else: i.left = TreeNode(int(data.pop())) stack2.append(i.left) if data[-1] == 'None': i.right = None data.pop() else: i.right = TreeNode(int(data.pop())) stack2.append(i.right) stack1 = stack2 return root
0 0
- leetcode之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
- LeetCode 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: Serialize and Deserialize Binary Tree
- [Leetcode]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
- Serialize and Deserialize Binary Tree -- leetcode
- 《老罗Android》学习之SQLite
- MongoDB_条件操作符
- 多线程总结上
- 设计模式之代理模式
- solr 为单独的core导入jar
- leetcode之Serialize and Deserialize Binary Tree
- 多线程总结下
- Android学习笔记—Service(1、start启动)
- Android断点下载实现
- Codeforces Round #226 (Div. 2)--C. Bear and Prime Numbers
- SolrCloud中的文件与Collection管理
- cocos2d-x CheckBox的使用
- ecneuqeSnoitatumreP.60
- static应用