1. Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
  2.  
  3. There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.
  4.  
  5. Example
  6. An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:
  7.  
  8. 3
  9. / \
  10. 9 20
  11. / \
  12. 15 7
  13. Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
  14.  
  15. You can use other method to do serializaiton and deserialization.

Serialization 和 Deserialization都是用BFS, Serialization注意要删除String末尾多余的“#”, Deserialization维护一个count指示当前TreeNode对应的值

  1. class Solution {
  2. /**
  3. * This method will be invoked first, you should design your own algorithm
  4. * to serialize a binary tree which denote by a root node to a string which
  5. * can be easily deserialized by your own "deserialize" method later.
  6. */
  7. public String serialize(TreeNode root) {
  8. // write your code here
  9. StringBuffer res = new StringBuffer();
  10. if (root == null) return res.toString();
  11. LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
  12. queue.offer(root);
  13. res.append(root.val);
  14. while (!queue.isEmpty()) {
  15. TreeNode cur = queue.poll();
  16. if (cur.left != null) queue.offer(cur.left); //add children to the queue
  17. if (cur.right != null) queue.offer(cur.right);
  18. res.append(",");
  19. if (cur.left != null) {
  20. res.append(cur.left.val);
  21. }
  22. else res.append("#");
  23. res.append(",");
  24. if (cur.right != null) {
  25. res.append(cur.right.val);
  26. }
  27. else res.append("#");
  28. }
  29. int i = res.length()-1;
  30. while (i>=0 && res.charAt(i)=='#') {
  31. res.deleteCharAt(i);
  32. res.deleteCharAt(i-1);
  33. i -= 2;
  34. }
  35. return res.toString();
  36. }
  37.  
  38. /**
  39. * This method will be invoked second, the argument data is what exactly
  40. * you serialized at method "serialize", that means the data is not given by
  41. * system, it's given by your own serialize method. So the format of data is
  42. * designed by yourself, and deserialize it here as you serialize it in
  43. * "serialize" method.
  44. */
  45. public TreeNode deserialize(String data) {
  46. // write your code here
  47. if (data==null || data.length()==0) return null;
  48. String[] arr = data.split(",");
  49. int len = arr.length;
  50. int count = 0;
  51. TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
  52. LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
  53. queue.offer(root);
  54. count++;
  55. while (!queue.isEmpty()) {
  56. TreeNode cur = queue.poll();
  57. String left="", right="";
  58. if (count < len) {
  59. left = arr[count];
  60. count++;
  61. if (!left.equals("#")) {
  62. cur.left = new TreeNode(Integer.parseInt(left));
  63. queue.offer(cur.left);
  64. }
  65. else cur.left = null;
  66. }
  67. else cur.left = null;
  68.  
  69. if (count < len) {
  70. right = arr[count];
  71. count++;
  72. if (!right.equals("#")) {
  73. cur.right = new TreeNode(Integer.parseInt(right));
  74. queue.offer(cur.right);
  75. }
  76. else cur.right = null;
  77. }
  78. else cur.right = null;
  79. }
  80. return root;
  81. }
  82. }

Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)的更多相关文章

  1. Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum =

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  2. [LeetCode] 106. Construct Binary Tree from Postorder and Inorder Traversal_Medium tag: Tree Traversal

    Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  3. 17.1.4 Replication and Binary Logging Options and Variables 复制和Binary logging 选项和变量

    17.1.4 Replication and Binary Logging Options and Variables 复制和Binary logging 选项和变量 下面的章节包含信息关于mysql ...

  4. LintCode-Serialization and Deserialization Of Binary Tree

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  5. [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal_Medium tag: Tree Traversal

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  6. 108. Convert Sorted Array to Binary Search Tree 109. Convert Sorted List to Binary Search Tree -- 将有序数组或有序链表转成平衡二叉排序树

    108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascendin ...

  7. 102. Binary Tree Level Order Traversal + 103. Binary Tree Zigzag Level Order Traversal + 107. Binary Tree Level Order Traversal II + 637. Average of Levels in Binary Tree

    ▶ 有关将一棵二叉树转化为二位表的题目,一模一样的套路出了四道题 ▶ 第 102 题,简单的转化,[ 3, 9, 20, null, null, 15, 7 ] 转为 [ [ 15, 7 ] , [ ...

  8. Data Structure Binary Tree: Lowest Common Ancestor in a Binary Tree

    http://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ #include <iostream> #in ...

  9. Data Structure Binary Tree: Print ancestors of a given binary tree node without recursion

    http://www.geeksforgeeks.org/print-ancestors-of-a-given-binary-tree-node-without-recursion/ #include ...

随机推荐

  1. C++ - 扩展欧几里德算法非递归实现

    #include <iostream> using namespace std; int x, y; void get_x_y(int a, int b){ int q, r[3], s[ ...

  2. 搭建一个Flv视频播放服务器

    搭建一个Flv视频播放服务器 热度 15已有 11511 次阅读2009-11-2 22:27 |关键词:服务器 视频 flv 播放 文档 错漏 经过一天的努力,查了好多资料,终于搞定了Flv视频服务 ...

  3. ASP.NET MVC 4下 Code First 数据库迁移

     一.命令开启 1.打开控制台:视图->其他窗口->程序包管理器控制台: 2.启动数据库迁移,执行命令:enable-migrations 创建成功后会新增migrations目录等. 若 ...

  4. PowerDesigner生成SQL Server 2008脚本注释乱码的问题

    [%OWNER%?[.O:[execute ][exec ]]sp_addextendedproperty [%R%?[N]]'MS_Description', N[%R%?[N]]%.q:COMME ...

  5. Ubuntu+Redis主从配置

    软件环境: OS:ubuntu-12.04-desktop-amd64 Redis:redis-2.8.13.tar.gz TCL:tcl8.6.2-src.tar.gz VMware:vmware ...

  6. for循环数据节点

    1.需要实现的功能,动态填充多条银行卡信息 2.dom结构 3.数据节点 4.实现方式 //获取银行卡基本信息 CmnAjax.PostData("Handler/Users/Users.a ...

  7. 修改OpenCart系统配置

    后台修改admin配置文件和修改根目录下的config.php <?php// HTTPdefine('HTTP_SERVER', 'http://网站域名/');define('HTTP_IM ...

  8. grok

    http://udn.yyuap.com/doc/logstash-best-practice-cn/filter/grok.html

  9. https://my.oschina.net/huangyong/blog/161419

    https://my.oschina.net/huangyong/blog/161419

  10. Advanced REST client的使用说明

    1.  为什么要使用REST Client 在实际企业开发过程中经常会有这样的需求: 1.我当前开发的这个系统是需要调用其他系统的接口,也就是我们需要频繁的测试接口,尝试不同的入参参数去查看返回结果, ...