Skip to content
New issue

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. 二叉树的序列化与反序列化 #18

Open
zpc7 opened this issue Jul 31, 2022 · 0 comments
Open

297. 二叉树的序列化与反序列化 #18

zpc7 opened this issue Jul 31, 2022 · 0 comments
Labels
困难 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Jul 31, 2022

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); // 构建的入口
};
@zpc7 zpc7 added 困难 LeetCode 难度定级 JS labels Jul 31, 2022
@zpc7 zpc7 removed the JS label Aug 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
困难 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant