`
hcx2013
  • 浏览: 83057 次
社区版块
存档分类
最新评论

Serialize and Deserialize Binary Tree

阅读更多

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.

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
        	return "#!";
        }
        String res = root.val + "!";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
    	String[] split = data.split("!");
    	LinkedList<String> queue = new LinkedList<>();
    	for (int i = 0; i < split.length; i++) {
    		queue.offer(split[i]);
		}
    	return reconPreOrder(queue);
    }

	private TreeNode reconPreOrder(LinkedList<String> queue) {
		// TODO Auto-generated method stub
		String poll = queue.poll();
		if (poll.equals("#")) {
			return null;
		}
		TreeNode head = new TreeNode(Integer.valueOf(poll));
		head.left = reconPreOrder(queue);
		head.right = reconPreOrder(queue);
		return head;
	}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

 

2
0
分享到:
评论

相关推荐

    Serialize and Deserialize Java 示例程序

    Serialize and Deserialize Java 示例程序。简单来讲,它的数据格式与json类似,但是在存储时对数字、多字节字符、数组等都做了很多优化,减少了无用的字符,二进制格式,也保证不用字符化带来额外的存储空间的增加...

    leetcode添加元素使和等于-leetcode:我的leetcode解决方案

    Deserialize Binary Tree Minimum Window Substring C++ STL中常见容器的时间复杂度 map, set, multimap, and multiset 上述四种容器采用红黑树实现,红黑树是平衡二叉树的一种。不同操作的时间复杂度近似为: 插入:O...

    serialize binary tree.pdf

    How can we implement trees with nodes that have &gt; 2 children?

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    C#序列化与反序列化(Serialize,Deserialize)实例详解

    本文实例讲述了C#序列化与反序列化(Serialize,Deserialize)实现方法。分享给大家供大家参考。具体分析如下: 如果要保存运行程序过程的数据要么保存到数据库中,要么新建一个普通的文件,然后把数据保存进去.但是这...

    Android代码-yamlbeans

    YamlBeans makes it easy to serialize and deserialize Java object graphs to and from YAML, a human-friendly data format. Replace XML and properties files with YAML for more expressive power (lists, ...

    Android代码-CacheUtilsLibrary

    This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize and deserialize these data. 中文版请看这里。 Gradle compile '...

    The Modern C++ Challenge

    Serialize and deserialize JSON and XML data Perform encryption and signing to facilitate secure communication between parties Embed and use SQLite databases in your applications Use threads and ...

    form-serialize-and-calculate.html

    form-serialize-and-calculate.html

    opg:Rust OpenAPI 3.0文档生成器

    use serde :: {Serialize, Deserialize}; #[derive(Serialize, Deserialize, OpgModel)] #[serde(rename_all = "camelCase" )] #[opg( "Simple enum" )] enum SimpleEnum { Test, Another, Yay, } #[derive...

    .net Newtonsoft.Json 4.0 release

    you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily ...

    :locked_with_key: 加密所有的 Serialize。

    Alice Bob+-----------------------------------+ +-----------------------------------+| #[derive(Serialize, Deserialize)] | | #[derive(Serialize, Deserialize)] || struct Message | | struct Message |+--...

    Json.NET 6.0 R3 For.NET(2.0-4.5)

    Json.NET Json.NET is a popular ... you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

    javalruleetcode-leetcode:更多信息请访问Gitbook:https://wentao-shao.gitbook.io/

    Tree](Basic-Knowledge/Binary tree.md) Serialize And Deserialize Bit 1.position 2.sequence Sell Stock 区间型 矩阵坐标 Word Ladder Add Two Numbers Matrix Spiral Matrix Mergesort [Algorithm Swap]...

    wactor:基于疯子的wasm actor系统

    use serde :: {Deserialize, Serialize}; use wactor :: * ; struct Counter { count: u32 , } #[derive(Serialize, Deserialize)] enum Input { AddOne, } #[derive(Serialize, Deserialize, PartialEq, Debug)] ...

    serialize-stl-binary:STL二进制序列化

    安装$ npm install serialize-stl-binary用法 var serializeSTL = require ( 'serialize-stl-binary' ) ;var fs = require ( 'fs' ) ;var mesh = { positions : [ [ - 1.0 , 0.0 , 0.0 ] , [ 0.0 , 1.0 , 0.0 ] , [ ...

    fondant:基于宏的配置管理库

    软糖 ···· fondant是一个基于宏的库,... // the struct has to derive Serialize, Deserialize and Default use fondant :: Configure; use serde :: {Serialize, Deserialize}; #[derive(Configure, Serialize, D

    Json NET 6 0 R8 For NET 2 0 4 5

    t have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects."&gt;Json.NET is a popular high-performance ...

    适用于疯子的超小型actor API包装器-Rust开发

    struct Counter {count:u32,}#[derive(Serialize,Deserialize)]枚举输入{AddOne,}#[derive(Serialize,Deserialize,PartialEq,Debug)]枚举输出{Count(u32),} impl Actor for Counte

Global site tag (gtag.js) - Google Analytics