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.

Solution:

 /**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
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) {
String res = "";
if (root==null) return res; List<TreeNode> nodeList = new ArrayList<TreeNode>();
nodeList.add(root);
int index = 0;
res = Integer.toString(nodeList.get(0).val);
while (index<nodeList.size()){
TreeNode cur = nodeList.get(index);
if (cur==null){
res += ",#,#";
} else {
if (cur.left!=null){
nodeList.add(cur.left);
res += ","+cur.left.val;
} else res += ",#";
if (cur.right!=null){
nodeList.add(cur.right);
res += ","+cur.right.val;
} else res += ",#";
}
index++;
} return res;
} /**
* 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) {
if (data.isEmpty()) return null;
String[] temp = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(temp[0]));
List<TreeNode> nodeList = new ArrayList<TreeNode>();
nodeList.add(root);
int cur = 0, next = 1;
while (cur<nodeList.size()){
TreeNode curNode = nodeList.get(cur);
if (curNode==null) cur++;
else {
int left = next;
int right = next+1;
if (next<temp.length){
if (temp[next].equals("#")) nodeList.add(null);
else {
TreeNode leftChild = new TreeNode(Integer.parseInt(temp[next]));
curNode.left = leftChild;
nodeList.add(leftChild);
}
}
if (next+1<temp.length){
if (temp[next+1].equals("#")) nodeList.add(null);
else {
TreeNode rightChild = new TreeNode(Integer.parseInt(temp[next+1]));
curNode.right = rightChild;
nodeList.add(rightChild);
}
}
next += 2;
cur++;
}
} return root;
}
}

LintCode-Serialization and Deserialization Of Binary Tree的更多相关文章

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

  2. LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)

    题目描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将 ...

  3. [LintCode] Binary Tree Serialization

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

  4. [LeetCode] Verify Preorder Serialization of a Binary Tree 验证二叉树的先序序列化

    One way to serialize a binary tree is to use pre-oder traversal. When we encounter a non-null node, ...

  5. 【LeetCode】Verify Preorder Serialization of a Binary Tree(331)

    1. Description One way to serialize a binary tree is to use pre-order traversal. When we encounter a ...

  6. LeetCode Verify Preorder Serialization of a Binary Tree

    原题链接在这里:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ 题目: One way to ...

  7. LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree

    One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...

  8. Verify Preorder Serialization of a Binary Tree

    One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...

  9. 331. Verify Preorder Serialization of a Binary Tree

    One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...

随机推荐

  1. SpringMVC使用静态资源

    1.Servlet配置如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&quo ...

  2. repeater标签双重循环的使用

    在网站开发中,.NET中的repeater标签几乎是笔者首选,也是唯一一个不会生成多余元素的标签,所有样式都是自定义的,这点类似 struts中的<s:iterator/>标签. 在日常编 ...

  3. 线性回归的Spark实现 [Linear Regression / Machine Learning / Spark]

    1- 问题提出 2- 线性回归 3- 理论推导 4- Python/Spark实现 # -*- coding: utf-8 -*- from pyspark import SparkContext t ...

  4. 第四章_PHP基本语法(2)

    1.常量的声明 在PHP中,定义常量使用define()函数来实现 2.魔术常量 名称 作用 __LINE__ 返回文件中的当前行号 __FILE__ 返回该文件的完整路径和文件名 __DIR__ 返 ...

  5. 安装C-Kermit串口访问开发板

    linux下的串口调试工具主要有minicom和kermit. minicom的安装与使用见博文: http://www.cnblogs.com/tanghuimin0713/p/3562218.ht ...

  6. html Doctype作用?

    Doctype它主要的作用来声明html的版本 <!Doctype html>这是html5的 不写可能会造成html5的功能不能用(具体会不会出错就要看浏览器的容错性)

  7. 设置peoplecode trace

    Configuring PeopleCode Trace Select PeopleTools, Utilities, Debug, Trace PeopleCode to access the Tr ...

  8. js dom 操作

    JS的DOM操作   1DOM是文档对象模型,这种模型为树模型:文档是指标签文档,对象是指文档中每个元素:模型是指抽象化的东西. 2间隔与延迟间隔执行一段代码(函数):window.setInterv ...

  9. 二、MongoDB的基础知识简介

    1.文档.集合和数据库 a).文档:因为MongoDB是面向文档的数据库,那么可想而知文档是它的基本单元,相当于关系型数据库中的行! Ⅰ.它是由键值对组成的一个有序集:注:键不能为空且是字符串类型的. ...

  10. 类似桌面背景壁纸随手指滑动--第三方开源--BackgroundViewPager

    Android BackgroundViewPager在github上的项目主页是:https://github.com/MoshDev/BackgroundViewPager 下载下来即可运行