Tree <-> String->
When you use network to transport a tree or a graph, you can not pass the momery. So usually you have to use a string to transport!
- Binary Search Tree
- Complete Tree
- Full Tree
297. Serialize and Deserialize Binary Tree
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
29class Codec:
def serialize(self, root):
res = []
def dfs(node):
if not node:
res.append("None")
return
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(res)
def deserialize(self, data):
def helper(q):
if tokens[0] == "None":
q.popleft()
return None
root = TreeNode(q.popleft())
root.left = helper(q)
root.right = helper(q)
return root
tokens = collections.deque(data.split(','))
root = helper(tokens)
return root
Tree Serialization
426. Convert Binary Search Tree to Sorted Doubly Linked List
O(n) extra space
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# Time : O(n), Space : O(n)
class Solution(object):
def treeToDoublyList(self, root):
if not root:
return None
res = []
self.inOrder(root, res)
n = len(res)
for i in xrange(n):
res[i].right = res[i+1] if i < n-1 else res[0]
res[i].left = res[i-1]
return res[0]
def inOrder(self, root, res):
if not root:
return
self.inOrder(root.left, res)
res.append(root)
self.inOrder(root.right, res)in-place
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24# Time : O(n), Space : O(1)
class Solution(object):
def treeToDoublyList(self, root):
if not root:
return None
self.prev = None
self.head = None
self.inOrder(root)
self.prev.right = self.head
self.head.left = self.prev
return self.head
def inOrder(self, root):
if not root:
return
self.inOrder(root.left)
if self.prev:
root.left = self.prev
self.prev.right = root
else:
self.head = root
self.prev = root
self.inOrder(root.right)
Tree De-Serialization
- We can NOT construct a Binary Tree using postorder and preorder
106. Construct Binary Tree from Inorder and Postorder Traversal
- Global Question divide to sub problem
1 | class Solution(object): |
105. Construct Binary Tree from Preorder and Inorder Traversal
1 | class Solution(object): |
Construct Binary Tree from Inorder and level Order
114. Flatten Binary Tree to Linked List
1 | class Solution(object): |