-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserializeAndDeserialize.ts
54 lines (41 loc) · 1.24 KB
/
serializeAndDeserialize.ts
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
52
53
54
import { TreeNode } from 'classes/BinaryTreeNode'
import { serialize } from '0001-1000/297/serializeAndDeserialize'
// Notice that the root is the root of the BST
// <Recursion, DFS>
// Time: O(n)
// Space: O(n)
/*
* Encodes a tree to a single string. (IMPORTED)
*/
/*
* Decodes your encoded data to tree.
*/
function dfsDeserialize(dataList: string[], lower = -Infinity, upper = Infinity): TreeNode | null {
// edge cases
if (dataList[0] === '#') {
dataList.shift()
return null
}
const valLast = parseInt(dataList[dataList.length - 1], 10)
if (valLast < lower || valLast > upper) {
return null
}
const val = parseInt(dataList[0], 10)
const node = new TreeNode(val)
dataList.shift()
node.left = dfsDeserialize(dataList, lower, val)
node.right = dfsDeserialize(dataList, val, upper)
return node
}
function deserialize(data: string): TreeNode | null {
const dataList = data.split(',')
return dfsDeserialize(dataList)
}
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
function serializeAndDeserialize(root: TreeNode | null): TreeNode | null {
return deserialize(serialize(root))
}
export { deserialize, serialize, serializeAndDeserialize }