-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialize.js
41 lines (34 loc) · 878 Bytes
/
serialize.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
/**
* Serialize a binary tree to array.
*
* @param {TreeNode|Object} tree - Binary tree.
* @returns {Array} Array representation of the binary tree.
*/
const serialize = (tree) => {
if (!tree) {
return null
}
const result = [tree.val]
const nodeQueue = [tree]
let lastValueIndex = 0
while (nodeQueue.length > 0) {
const node = nodeQueue.shift()
if (node.left === null || node.left === undefined) {
result.push(null)
} else {
result.push(node.left.val)
nodeQueue.push(node.left)
lastValueIndex = result.length - 1
}
if (node.right === null || node.right === undefined) {
result.push(null)
} else {
result.push(node.right.val)
nodeQueue.push(node.right)
lastValueIndex = result.length - 1
}
}
result.splice(lastValueIndex + 1)
return result
}
module.exports = serialize