题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
/*class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param root TreeNode类
* @return TreeNode类
*/
//二叉树的序列化和反序列化
//序列化:前序遍历、中序遍历、后序遍历
//反序列化:前序遍历、后序遍历
// const result = []
// const NULL = '#'
// const str = ','
// export function Serialize(root: TreeNode): string {
// if(root == null){
// result.push(NULL)
// return
// }
// //前序遍历
// result.push(root.val)
// result.push(str)
// Serialize(root.left)
// result.push(str)
// Serialize(root.right)
// return result.join("")
// }
// export function Deserialize(str: string): TreeNode {
// // 还原为二叉树
// //转化为数组
// if(str.length == 0)return null
// const array = str.split(',')
// const first = array.shift()
// if(first == NULL)return null
// const root = new TreeNode(Number(first))
// root.left = Deserialize(array.join(","))
// root.right = Deserialize(array.join(","))
// return root
// }
const result = []
const NULL = '#'
export function Serialize(root: TreeNode): string {
if (root === null) {
result.push(NULL);
result.push(',');
return result.join("");
}
// 前序遍历
result.push(root.val);
result.push(',');
Serialize(root.left);
Serialize(root.right);
return result.join("");
}
export function Deserialize(str: string): TreeNode {
// 还原为二叉树
//转化为数组
if (str.length === 0) return null;
const array = str.split(',');
function buildTree(): TreeNode {
if(array.length == 0)return null
const first = array.shift();
if (first === NULL) return null;
const root = new TreeNode(Number(first));
root.left = buildTree();
root.right = buildTree();
return root;
}
return buildTree();
}


