/* * Encodes a tree to a single string. */ functionserialize(root: TreeNode | null): string { if (root === null) return'' const preorder = [] traverse(root, preorder) return preorder.join(',') };
functionbuild(preorder: string[]): TreeNode | null { if (preorder.length === 0) returnnull const rootVal = preorder.shift() if (rootVal === '#') returnnull const root = newTreeNode(Number(rootVal)) root.left = build(preorder) root.right = build(preorder) return root } /* * Decodes your encoded data to tree. */ functiondeserialize(data: string): TreeNode | null { if (data === '') returnnull const preorder = data.split(',') returnbuild(preorder) };
/** * Your functions will be called as such: * deserialize(serialize(root)); */