js-challenges
js-challenges copied to clipboard
序列化二叉树
/**
* 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 str = '';
let reSerialize = (root) => {
if (root === null){
str += '#,'
} else {
str += root.val + ',';
root.left = reSerialize(root.left);
root.right = reSerialize(root.right);
}
return str;
}
return reSerialize(root);
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
let arr = data.split(',')
console.log(arr);
const reDeserialize = (arr) => {
if(arr[0] === '#') {
arr.shift();
return null;
}
const root = new TreeNode(parseInt(arr[0]));
arr.shift();
root.left = reDeserialize(arr);
root.right = reDeserialize(arr);
return root;
}
return reDeserialize(arr);
};
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
var serialize = function(root) {
return JSON.stringify(root)
};
var deserialize = function(data) {
return JSON.parse(data)
};
var serialize = function(root) {
if(!root) return 'N'
let left = serialize(root.left)
let right = serialize(root.right)
return `${root.val},${left},${right}`
};
var deserialize = function(data) {
const arr = data.split(',')
function fn(){
let item = arr.shift()
if(item==='N') return null
const root = new TreeNode(item)
root.left = fn()
root.right = fn()
return root
}
return fn()
};