Skip to content

Commit 704805f

Browse files
authored
Create problem3
1 parent 8e4c2ba commit 704805f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

daily_coding_problems/problem3

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Daily Coding Problem #3
2+
Problem
3+
This problem was asked by Google.
4+
5+
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
6+
7+
For example, given the following Node class
8+
9+
class Node:
10+
def __init__(self, val, left=None, right=None):
11+
self.val = val
12+
self.left = left
13+
self.right = right
14+
The following test should pass:
15+
16+
node = Node('root', Node('left', Node('left.left')), Node('right'))
17+
assert deserialize(serialize(node)).left.left.val == 'left.left'
18+
Solution
19+
There are many ways to serialize and deserialize a binary tree, so don't worry if your solution differs from this one. We will be only going through one possible solution.
20+
21+
We can approach this problem by first figuring out what we would like the serialized tree to look like. Ideally, it would contain the minimum information required to encode all the necessary information about the binary tree. One possible encoding might be to borrow S-expressions from Lisp. The tree Node(1, Node(2), Node(3)) would then look like '(1 (2 () ()) (3 () ()))', where the empty brackets denote nulls.
22+
23+
To minimize data over the hypothetical wire, we could go a step further and prune out some unnecessary brackets. We could also replace the 2-character '()' with '#'. We can then infer leaf nodes by their form 'val # #' and thus get the structure of the tree that way. Then our tree would look like 1 2 # # 3 # #.
24+
25+
def serialize(root):
26+
if root is None:
27+
return '#'
28+
return '{} {} {}'.format(root.val, serialize(root.left), serialize(root.right))
29+
30+
def deserialize(data):
31+
def helper():
32+
val = next(vals)
33+
if val == '#':
34+
return None
35+
node = Node(int(val))
36+
node.left = helper()
37+
node.right = helper()
38+
return node
39+
vals = iter(data.split())
40+
return helper()
41+
This runs in O(N) time and space, since we iterate over the whole tree when serializing and deserializing.

0 commit comments

Comments
 (0)