Authored by Tony Feng
Created on May 9th, 2022
Last Modified on May 9th, 2022
Task 1 - Q37. 序列化二叉树
Question
请实现两个函数,分别用来序列化和反序列化二叉树。你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import deque
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root: return "[]"
ans = []
queue = deque()
queue.append(root)
while queue: # BFS
node = queue.popleft()
if node:
ans.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
ans.append("null")
return '[' + ",".join(ans) + ']'
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data or data == "[]": return None
data = data.strip('[').strip(']').split(',')
root = TreeNode(int(data[0]))
queue = deque()
queue.append(root)
i = 1
while queue:
node = queue.popleft()
if data[i] != "null": # Check the left node
node.left = TreeNode(int(data[i]))
queue.append(node.left)
i += 1
if data[i] != "null": # Check the right node
node.right = TreeNode(int(data[i]))
queue.append(node.right)
i += 1
return root
|
Explanation
deserialize
and serialize
:
- Time Complexity: O(N)
- Space Complexity: O(N)
Task 2 - Q38. 字符串的排列
Question
输入一个字符串,打印出该字符串中字符的所有排列。输入:s = "abc"
; 输出:["abc","acb","bac","bca","cab","cba"]
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Solution:
def permutation(self, s: str) -> List[str]:
ans = set() # Avoid duplicates
visited = [0 for _ in range(len(s))]
def back(path):
if len(path) == len(s):
ans.add(path[:])
return
for i in range(0, len(s)):
if visited[i] == 0:
visited[i] = 1
back(path + s[i])
visited[i] = 0 # Go back
back("")
return list(ans)
|
Explanation
- Time Complexity: O(N! * N)
- DFS: N * (N-1) * (N-2) * … * 1
- Set -> List: O(N)
- Space Complexity: O(N2)