序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
递归
/**
* 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) {
if (!root) return 'X'
return `${root.val},${serialize(root.left)},${serialize(root.right)}`
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
const stack = data.split(',')
const order = (stack) => {
const cur = stack.shift()
if (cur === 'X') return null
const root = new TreeNode(cur)
root.left = order(stack)
root.right = order(stack)
return root
}
return order(stack)
};
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
栈
/**
* 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) {
const res = [], stack = [root]
while(stack.length) {
const root = stack.shift()
if (root) {
res.push(root.val)
stack.push(root.left)
stack.push(root.right)
} else {
res.push('X')
}
}
return res.join(',')
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
if (data === 'X') return null
const list = data.split(',')
const root = new TreeNode(list[0])
const stack = [root]
let cursor= 1;
while (cursor < list.length) {
const node = stack.shift()
if (list[cursor] !== 'X') {
const left = new TreeNode(list[cursor])
node.left = left
stack.push(left)
}
if (list[cursor+1] !== 'X') {
const right = new TreeNode(list[cursor+1])
node.right = right
stack.push(right)
}
cursor += 2
}
return root
};
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/