Time: 30 minutes
Serialization is simple and can be solved using BFS
Deserialization requires the use of the properties of a binary tree, that is, the child nodes of the i-th node are (i + 1) * 2 - 1 and (i + 1) * 2 respectively.
- Find the parent node and push it onto the stack. At this point, pointer i is at the parent node’s val.
- Pop the parent node from the stack and find the parent node’s left and right nodes. The pointers find their values twice according to the rules. Push the left and right nodes onto the stack. i++
- Repeat 1.
var serialize = function(root) {
if (!root) return []
var que = [root]
var res = []
while(que.length) {
var cur = que.shift()
if (cur) {
res.push(cur.val);
que.push(cur.left); que.push(cur.right);
} else {
res.push('null');
}
}
return res.join(',')
};/** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */var deserialize = function(data) {
if (!data.length) return null var nodes = data.split(',')
var i = 0
var root = new TreeNode(nodes[i])
var que = [root]
while ( que.length) {
var node = que.shift()
var left = nodes[ (i + 1) * 2 - 1]
var right = nodes[ (i + 1) * 2]
if (left !== 'null') {
node.left = new TreeNode(left)
que.push(node.left)
} else {
node.left = null }
if (right !== 'null') {
node.right = new TreeNode(right)
que.push(node.right)
} else {
node.right = null }
i++ }
return root};