Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)
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)的更多相关文章
- 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 ...
- [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 ...
- 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 ...
- 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 ...
- [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 ...
- 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 ...
- 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 ] , [ ...
- 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 ...
- 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 ...
随机推荐
- laravel 外键schema RBAC
$table->bigIncrements('id') ; Incrementing ID (primary key) using a " UNSIGNED BIG INTEGE ...
- 以大写字母“J”来展示位图
'0' => '00011100001111111001100011011000001111000001111000001111000001111000001111000001111000001 ...
- [转]GPS纠偏算法,适用于google,高德体系的地图
此文是转的,算法没验证过,只是记录一下. GPS纠偏算法,适用于google,高德体系的地图,精确度还比较高.我试了一下比高德本身的纠偏还精确点. /** * gps纠偏算法,适用于google,高德 ...
- StartSSL免费证书申请笔记
第一步:申请startssl账号 填写相应信息后,你所填写的邮箱会收到邮件 里面有一个用来验证的验证码 输入得到的.... 注册成功后会安装数字证书(注意:注册过程中没有叫输入账号密码,这也是通过证认 ...
- css层叠选择
首先声明一下CSS三大特性——继承.优先级和层叠.继承即子类元素继承父类的样式,比如font-size,font-weight等f开头的css样式以及text-align,text-indent等t开 ...
- nrf51822裸机教程-GPIOTE
GPIO通常都会具有中断功能,上一讲的GPIO中并没有涉及到中断的相关寄存器. 51822将GPIO的中断相关做成了一个单独的模块GPIOTE,这个模块不仅提供了GPIO的中断功能,同时提供了 通过t ...
- Java实验报告五:Java网络编程及安全
Java实验报告五:Java网络编程及安全 ...
- Java Socket Option
选项 public final static int TCP_NODELAY = 0x0001; public final static int SO_REUSEADDR = 0x04; public ...
- 在Windows 环境下编译Qt静态库(QT5.32)
参考链接 Qt5.3 Tools and Versions MinGW ICU ActivePerl Qt 安装MinGW工具链环境 这里在Win32环境下要安装一个MinGW工具链,这里最好是先安装 ...
- Qt 之 设置窗口边框的圆角(使用QSS和PaintEvent两种方法)
Qt在设置窗口边框圆角时有两种方式,一种是设置样式,另一种是在paintEvent事件中绘制窗口.下面分别叙述用这两种方式来实现窗口边框圆角的效果. 一.使用setStyleSheet方法 this- ...