AcWing 50. 序列化二叉树 JavaScript BFS
原题链接
困难
作者:
amifed
,
2021-03-23 17:58:20
,
所有人可见
,
阅读 323
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root) {
let list = [];
const q = [root];
while (q.length) {
let p = q.shift();
list.push(p ? p.val : null);
if (p) {
q.push(p.left);
q.push(p.right);
}
}
return list.join(',');
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
data = data.split(',').map(x => parseInt(x));
if (isNaN(data[0])) return null;
const root = new TreeNode(data[0]);
const q = [root];
let idx = 1;
while (q.length) {
let p = q.shift();
p.left = isNaN(data[idx]) ? null : new TreeNode(data[idx]);
++idx;
if (p.left) q.push(p.left);
p.right = isNaN(data[idx]) ? null : new TreeNode(data[idx]);
++idx;
if (p.right) q.push(p.right);
}
return root;
};