-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0297_serializeAndDeserializeBinaryTree.js
84 lines (69 loc) · 1.82 KB
/
0297_serializeAndDeserializeBinaryTree.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @typedef {Object} TreeNode
* @description Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @summary Serialize and Deserialize Binary Tree {@link https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/}
* @description Write functions to serialize and deserialize binary tree.
* Space O(n) - For both serialize and deserialize, we store every node.
* Time O(n) - For both serialize and deserialize, we traverse every node.
*/
/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
const serialize = root => {
const queue = [root];
const result = [];
while (queue.length) {
const current = queue.shift();
if (current === null) result.push('null');
else {
result.push(current.val);
queue.push(current.left);
queue.push(current.right);
}
}
while (result[result.length - 1] === 'null') {
result.pop();
}
return result.join(',');
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
const deserialize = string => {
if (string === '') return null;
const treeData = string.split(',');
const root = new TreeNode(+treeData.shift());
const queue = [root];
while (queue.length) {
const current = queue.shift();
if (treeData.length) {
const leftData = treeData.shift();
if (leftData !== 'null') {
const left = new TreeNode(+leftData);
current.left = left;
queue.push(current.left);
}
}
if (treeData.length) {
const rightData = treeData.shift();
if (rightData !== 'null') {
const right = new TreeNode(+rightData);
current.right = right;
queue.push(current.right);
}
}
}
return root;
};