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'.

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.

Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure: 3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input. You can use other method to do serializaiton and deserialization.

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

 class Solution {
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
public String serialize(TreeNode root) {
// write your code here
StringBuffer res = new StringBuffer();
if (root == null) return res.toString();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
res.append(root.val);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur.left != null) queue.offer(cur.left); //add children to the queue
if (cur.right != null) queue.offer(cur.right);
res.append(",");
if (cur.left != null) {
res.append(cur.left.val);
}
else res.append("#");
res.append(",");
if (cur.right != null) {
res.append(cur.right.val);
}
else res.append("#");
}
int i = res.length()-1;
while (i>=0 && res.charAt(i)=='#') {
res.deleteCharAt(i);
res.deleteCharAt(i-1);
i -= 2;
}
return res.toString();
} /**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
public TreeNode deserialize(String data) {
// write your code here
if (data==null || data.length()==0) return null;
String[] arr = data.split(",");
int len = arr.length;
int count = 0;
TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
count++;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
String left="", right="";
if (count < len) {
left = arr[count];
count++;
if (!left.equals("#")) {
cur.left = new TreeNode(Integer.parseInt(left));
queue.offer(cur.left);
}
else cur.left = null;
}
else cur.left = null; if (count < len) {
right = arr[count];
count++;
if (!right.equals("#")) {
cur.right = new TreeNode(Integer.parseInt(right));
queue.offer(cur.right);
}
else cur.right = null;
}
else cur.right = null;
}
return root;
}
}

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. Lazarus中system.length说明

    在system单元中我们有Length专门用来获取字符串宽度和数组宽度,下面例子来介绍他的功能. 定义: function Length(   S: AStringType ):Integer; fu ...

  2. JAVA的覆盖、继承和多态的详细解说.this和super的用法

    1. 继承: (1)子类的构造方法一定会调用父类的构造方法. (2)任何子类构造方法第一行肯定是this();或者super();两个择一. this();调用本类的其它构造方法.(传递相应参数调用相 ...

  3. This application failed to start because it could not find or load the Qt platform plugin "xcb".

    1.  copy      libQt5DBus.so.5 2.  add    QT_PLUGIN_PATH blog.csdn.net/windows_nt/article/details/242 ...

  4. 将所有程序设置XML集中到一个单独XML配置文件的方法:使用appSettings元素的configSource元素

    在.NET程序中,程序的配置文件默认都会放在程序根目录下的web.config(网站程序)或App.config(控制台等程序),在该配置文件中可以定义若干程序配置信息. 在此以网站程序为例,首先将下 ...

  5. C#窗体:关于DataGridView的数据源绑定字符串两个值得注意的问题

    无意间遇到的问题,然后就GOOGLE了下,搜到些资料,总结整理如下(注:是转载的) 1. LINQ的查询结果无法直接作为DataGridView的数据源 DataGridView的DataSource ...

  6. android source compiler

  7. 轮询、select、 epoll

    网卡设备对应一个中断号, 当网卡收到网络端的消息的时候会向CPU发起中断请求, 然后CPU处理该请求. 通过驱动程序 进而操作系统得到通知, 系统然后通知epoll, epoll通知用户代码.  一. ...

  8. 应中DOS中断显示字符串(摘自《汇编语言》王爽)

    data segment s1 db 'Good,better,best,$' s2 db 'Never let it rest,$' s3 db 'Till good is better,$' s4 ...

  9. 兼容加载Xml字符串

    var _loadXML = function(xmlString){ var xmlDoc=null; //支持IE浏览器 if(!window.DOMParser && windo ...

  10. 是什么在.NET程序关闭时阻碍进程的退出?

    在平时使用软件或是.NET程序开发的过程中,我们有时会遇到程序关闭后但进程却没有退出的情况,这往往预示着代码中有问题存在,不能正确的在程序退出时停止代码执行和销毁资源.这个现象有时并不容易被察觉,但在 ...