-
-
Notifications
You must be signed in to change notification settings - Fork 257
Open
Description
/**
* 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));
*/
Metadata
Metadata
Assignees
Labels
No labels