文件: root - text - article - 2019 - 12 - tree-serialization.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 702 次阅读, 19644 次搜索 | 171 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 702 次阅读, 19644 次搜索 | 171 个单词
| 浏览 | 博客存档
Hi, here's your problem today. This problem was recently asked by Apple:
You are given the root of a binary tree. You need to implement 2 functions:
1. serialize(root) which serializes the tree into a string representation
2. deserialize(s) which deserializes the string back to the original tree that it represents
For this problem, often you will be asked to design your own serialization format. However, for simplicity, let's use the pre-order traversal of the tree. Here's your starting point:
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 702 次阅读, 19644 次搜索 | 171 个单词 You are given the root of a binary tree. You need to implement 2 functions:
1. serialize(root) which serializes the tree into a string representation
2. deserialize(s) which deserializes the string back to the original tree that it represents
For this problem, often you will be asked to design your own serialization format. However, for simplicity, let's use the pre-order traversal of the tree. Here's your starting point:
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
# pre-order printing of the tree.
result = ''
result += str(self.val)
if self.left:
result += str(self.left)
if self.right:
result += str(self.right)
return result
def serialize(root):
# Fill this in.
def deserialize(data):
# Fill this in.
# 1
# / \
# 3 4
# / \ \
# 2 5 7
tree = Node(1)
tree.left = Node(3)
tree.left.left = Node(2)
tree.left.right = Node(5)
tree.right = Node(4)
tree.right.right = Node(7)
print serialize(tree)
# 1 3 2 # # 5 # # 4 # 7 # #
print deserialize('1 3 2 # # 5 # # 4 # 7 # #')
# 132547
猜您喜欢...
- Algorithm Interview: Determine If Linked List is Palindrome
- PHP Unit Tests on VPS Server
- Daily Interview Problem: Minimum Removals for Valid Parenthesis
- Daily Interview Problem: Sort Colors
- Daily Interview Problem: Product of Array Except Self
- Top K Frequent words
- Algorithm Interview: Subarray With Target Sum
- Consecutive Ones
- Floor and Ceiling of a Binary Search Tree
- Algorithm Interview: Lowest Common Ancestor of 2 Nodes in Binary Tree
©2006~2024 牛排过熟 - 0.00831 秒 - 2480.99 KB/s - 28 在线 内存: 492.84 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
牛排怎么做才好吃? | <meta name="机器人" content="不索引, 跟踪" />
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
评论 (0)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。