题解 | #序列化二叉树#
序列化二叉树
http://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类
*/
export function Serialize(root: TreeNode): string {
if (root === null) return '';
const res = []
const queue = [root]
while(queue.length) {
const node = queue.shift();
if (node) {
res.push(node.val);
queue.push(node.left)
queue.push(node.right)
} else {
res.push('#')
}
}
return res.join(',')
}
export function Deserialize(str: string): TreeNode {
if (!str) return null
const arr: string[] = str.split(',')
const root = new TreeNode(Number(arr.shift()))
const nodeList = [root]
while(arr.length) {
const node = nodeList.shift()
const left = arr.shift();
const right = arr.shift();
if (left !== '#') {
node.left = new TreeNode(Number(left))
nodeList.push(node.left)
}
if (right !== '#') {
node.right = new TreeNode(Number(right))
nodeList.push(node.right)
}
}
return root;
}