题目描述

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1/ \2   3/ \4   5

as “[1,2,3,null,null,4,5]”, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.


分析

我的最开始的思路是:先求树的深度h,把树中的每个结点(2^h-1)个结点,全部记录下来,即使是null。但是这样有些极端的测试用例会超时,比如树中每个结点只有右结点,树高1000。用这种方法要遍历2^h-1次,显然能够优化。

参考 how LeetCode OJ serializes a binary tree的序列化方式,下面的二叉树,序列化后的String可以是”1,2,3,null,null,4,null,5,null”,这种方法在序列化二叉树时,只用树结点数量规模的字符即可,省时省空间。

    1/ \2   3/ 4   /5

代码

第一种方法:超时的代码

    // Encodes a tree to a single string.public static String serialize(TreeNode root) {if (root == null) {return "";}StringBuffer sb = new StringBuffer();Deque<TreeNode> deque = new LinkedList<TreeNode>();deque.add(root);int n = (int) (Math.pow(2, maxDepth(root)) - 1);while (n-- != 0) {TreeNode p = deque.pop();if (p == null) {sb.append(",#");deque.add(null);deque.add(null);} else {sb.append("," + p.val);deque.add(p.left);deque.add(p.right);}}return sb.toString().substring(1);}// Decodes your encoded data to tree.public static TreeNode deserialize(String data) {if (data == null || data.length() == 0) {return null;}String[] s = data.split(",");TreeNode[] nodeArray = new TreeNode[s.length];for (int i = 0; i < nodeArray.length; i++) {if (!"#".equals(s[i])) {nodeArray[i] = new TreeNode(Integer.valueOf(s[i]));}}for (int parent = 0; parent < s.length / 2; parent++) {if (nodeArray[parent] == null) {continue;}nodeArray[parent].left = nodeArray[parent * 2 + 1];nodeArray[parent].right = nodeArray[parent * 2 + 2];}return nodeArray[0];}public static int maxDepth(TreeNode root) {if (root == null) {return 0;}int nLeft = maxDepth(root.left);int nRight = maxDepth(root.right);return nLeft > nRight ? (nLeft + 1) : (nRight + 1);}

第二种方法,AC的代码

    public String serialize(TreeNode root) {if (root == null) {return "";}StringBuffer sb = new StringBuffer();Deque<TreeNode> deque = new LinkedList<TreeNode>();deque.add(root);while (!deque.isEmpty()) {TreeNode p = deque.pop();if (p == null) {sb.append(",#");} else {sb.append("," + p.val);deque.add(p.left);deque.add(p.right);}}// 第一个元素前也有一个逗号,截取return sb.toString().substring(1);}public TreeNode deserialize(String data) {if (data == null || data.length() == 0) {return null;}String[] s = data.split(",");TreeNode[] node = new TreeNode[s.length];// 新建TreeNode,并初始化for (int i = 0; i < node.length; i++) {if (!"#".equals(s[i])) {node[i] = new TreeNode(Integer.valueOf(s[i]));}}int parent = 0;// 将结点连接起来for (int i = 0; parent * 2 + 2 < s.length; i++) {if (node[i] != null) {node[i].left = node[parent * 2 + 1];node[i].right = node[parent * 2 + 2];parent++;}}return node[0];}

LeetCode 297 Serialize and Deserialize Binary Tree相关推荐

  1. 297. Serialize and Deserialize Binary Tree

    Title 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据. 请设计一个算 ...

  2. lc 297. Serialize and Deserialize Binary Tree

    使用任意方法序列化一个二叉树. https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ 原来带有None作为结束标志的 ...

  3. [Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...

  4. leetcode 449. Serialize and Deserialize BST | 449. 序列化和反序列化二叉搜索树(BST后序遍历性质)

    题目 https://leetcode.com/problems/serialize-and-deserialize-bst/ 题解 本题的难点在于 利用 BST 的性质. 几个提示 根据后序遍历BS ...

  5. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  6. LeetCode: 104. Maximum Depth of Binary Tree

    题目 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the l ...

  7. leetcode 662. Maximum Width of Binary Tree | 662. 二叉树最大宽度(BFS)

    题目 https://leetcode.com/problems/maximum-width-of-binary-tree/ 题解 本题思路来源于二叉树的层序遍历. 层序遍历类似问题:leetcode ...

  8. LeetCode 662. Maximum Width of Binary Tree

    原题链接在这里:https://leetcode.com/problems/maximum-width-of-binary-tree/ 题目: Given a binary tree, write a ...

  9. LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)

    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shor ...

最新文章

  1. 来聊聊COCO数据集上两大霸榜模型-CBNet和DetectoRS
  2. LeetCode精讲 03无重复字符的最长子串(滑动窗口)
  3. 虚拟机中安装GHO文件配置说明
  4. termux怎么安装python库_Python termux-apt-repo包_程序模块 - PyPI - Python中文网
  5. [android笔记]常用的Uri例子
  6. rancher k8s docker 关系_【环境搭建】Ubuntu20.04通过rke部署K8S
  7. vs 2019 社区版许可证过期_Switch版《最终幻想12:黄道时代》对比PS4版 就没差
  8. 阿里云首席架构师解读开源和云端结合的三大优势
  9. 001-为什么Java能这么流行
  10. 第十一章 Shell常用命令与工具(一)
  11. java .class文件和.class文件区别是什么?
  12. 【论文笔记】MOBA类游戏中的强化学习论文5篇
  13. 黑马python培训网盘资源
  14. unity vr是加一个摄像机就行吗_梦工厂和皮克斯员工创办的Baobab谈互动叙事:传统动画与VR动画的探索...
  15. 电脑版微信多开显示网络代理服务器,电脑版微信多开的方法_电脑维护
  16. 德赛西威全球首发“Smart Solution”智能出行解决方案
  17. 艾永亮:疯传的秘密,一个手表如何一夜之间席卷全校?(下)
  18. excel常用快捷键(常用)
  19. 计算机开机按f1,开机要按F1怎么解决?电脑开机不按F1进去系统的方法
  20. 万户OA助力红豆集团信息化建设方案

热门文章

  1. 牛逼的uniapp+Java微信小程序商城来了
  2. 梯度下降算法公式推导
  3. [VCAP5] VCAP5-DCA DCD学习资料汇总 存储(VDCA510为主)
  4. 用树莓派搭建全功能NAS服务器(04):打造个人网盘系统优化
  5. Fiddler笔记(一)
  6. C# 十进制和十六进制转换
  7. 肾结石的诱因有哪些?
  8. UE4 时间变慢,时间子弹类似
  9. 说一说$emit和$on
  10. 电脑提示“nv1ddmkm.sys蓝屏”