We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
297. 二叉树的序列化与反序列化
参考题解: https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/
序列化为字符串:
const serialize = (root) => { if (root == null) { // 遍历到 null 节点 return 'X'; } const left = serialize(root.left); // 左子树的序列化结果 const right = serialize(root.right); // 右子树的序列化结果 return root.val + ',' + left + ','+ right; // 按 根,左,右 拼接字符串 };
反序列化为树结构:
const deserialize = (data) => { const list = data.split(','); // split成数组 const buildTree = (list) => { // 基于list构建当前子树 const rootVal = list.shift(); // 弹出首项,获取它的“数据” if (rootVal == "X") { // 是X,返回null节点 return null; } const root = new TreeNode(rootVal); // 不是X,则创建节点 root.left = buildTree(list); // 递归构建左子树 root.right = buildTree(list); // 递归构建右子树 return root; // 返回当前构建好的root }; return buildTree(list); // 构建的入口 };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
297. 二叉树的序列化与反序列化
参考题解: https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/
序列化为字符串:
反序列化为树结构:
The text was updated successfully, but these errors were encountered: