题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
function Serialize(pRoot)
{
if (pRoot === null) return '';
// 使用队列辅助迭代
const queue = [pRoot];
let res = ''
while(queue.length) {
let levelCount = queue.length; // 一层的数量
while(levelCount--) {
const node = queue.shift(); // 依次取出头节点
if (node === null) { // 如果未空,则使用 #
res+=',#'
} else {
res+=',' + node.val; // 否则,拼接数组
queue.push(node.left); // 将左右节点推出队列中
queue.push(node.right);
}
}
}
return res.slice(1);
}
function Deserialize(s)
{
if (s === '') return null;
const sArr = s.split(',')
const rootVal = sArr.shift();
const root = new TreeNode(rootVal);
const nodeQueue = [root];
while(sArr.length) {
// 获取父节点
const node = nodeQueue.shift();
// 获取节点值
const nodeLeftVal = sArr.shift();
const nodeRightVal = sArr.shift();
// 如果节点不为空
if (nodeLeftVal !== '#') {
node.left = new TreeNode(nodeLeftVal);
nodeQueue.push(node.left)
}
if (nodeRightVal !== '#') {
node.right = new TreeNode(nodeRightVal);
nodeQueue.push(node.right)
}
}
return root;
}
module.exports = {
Serialize : Serialize,
Deserialize : Deserialize
};