来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/serialize-and-deserialize-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。 设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。 编码的字符串应尽可能紧凑。

解答

把所有树节点转为字符串,然后再转为树,要考虑节点为 null 的情况

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * Encodes a tree to a single string.
  10. *
  11. * @param {TreeNode} root
  12. * @return {string}
  13. */
  14. var serialize = function(root) {
  15. if (!root) return '';
  16. let ret = [],
  17. stack = [ root ];
  18. while (stack.length) {
  19. const node = stack.shift();
  20. if (node?.val === 'undefined') {
  21. ret.push('')
  22. } else {
  23. ret.push(node?.val)
  24. }
  25. if (node) {
  26. stack.push(node.left);
  27. stack.push(node.right);
  28. }
  29. }
  30. return ret.toString();
  31. };
  32. /**
  33. * Decodes your encoded data to tree.
  34. *
  35. * @param {string} data
  36. * @return {TreeNode}
  37. */
  38. var deserialize = function(data) {
  39. if (!data) return null;
  40. const nodes = data.split(',');
  41. const firstNode = new TreeNode(nodes.shift());
  42. let stack = [ firstNode ];
  43. while (stack.length) {
  44. let temp = [];
  45. for (let node of stack) {
  46. if (node) {
  47. const leftVal = nodes.shift();
  48. node.left = leftVal ? new TreeNode(leftVal) : null;
  49. const rightVal = nodes.shift();
  50. node.right = rightVal ? new TreeNode(rightVal) : null;
  51. temp.push(node.left);
  52. temp.push(node.right);
  53. }
  54. }
  55. stack = temp;
  56. }
  57. return firstNode;
  58. };
  59. /**
  60. * Your functions will be called as such:
  61. * deserialize(serialize(root));
  62. */