博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Serialize and Deserialize Binary Tree & BST
阅读量:5966 次
发布时间:2019-06-19

本文共 4207 字,大约阅读时间需要 14 分钟。

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

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

思路

理论上说所有遍历的方法都可以。但是为了使serialize和deserialize的过程都尽量最简单,preorder是不错的选择。serialize的话,dfs比较好写,deserialize的话preorder和bfs比较好写。用“,”作为分隔符,“#”来表示null。例子里serialize之后结果就变成"1,2,3,#,#,4,5"。deserialize的时候用一个queue来保存string。

复杂度

Time: O(N), Space: O(N)

代码

// Encodes a tree to a single string.    public String serialize(TreeNode root) {        // base case        if(root == null) return "";        StringBuilder encoded = new StringBuilder();        encode(root, encoded);        return encoded.substring(1).toString();    }        private void encode(TreeNode root, StringBuilder sb) {        if(root == null) {            sb.append(",#");            return;        }        sb.append(",").append(root.val);        encode(root.left, sb);        encode(root.right, sb);    }    // Decodes your encoded data to tree.    public TreeNode deserialize(String data) {        // base case        if(data.length() == 0) return null;        Queue
q = new LinkedList(Arrays.asList(data.split(","))); return decode(q); } private TreeNode decode(Queue
q) { if(q.isEmpty()) return null; String cur = q.poll(); if(cur.equals("#")) return null; TreeNode root = new TreeNode(Integer.valueOf(cur)); root.left = decode(q); root.right = decode(q); return root; }

449. Serialize and Deserialize BST

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.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

思路

这道题和之前不同,一般的树变成了BST,而且要求是as compact as possible。还是可以用preorder,还是需要分隔符,但是null就不需要保存了。deserialize部分要变得复杂,left的值总是小于root的值,right的值总是大于root的值,根据这个每次recursion的时候把左边的值都放到另一个queue里面,剩下的就是右边的值。

复杂度

Time: O(N^2), Space: O(N)

代码

// Encodes a tree to a single string.    public String serialize(TreeNode root) {        // base case        if(root == null) return "";        StringBuilder encoded = new StringBuilder();        encode(root, encoded);        return encoded.substring(1).toString();    }        private void encode(TreeNode root, StringBuilder sb) {        if(root == null) return;        sb.append(",").append(root.val);        encode(root.left, sb);        encode(root.right, sb);    }        // Decodes your encoded data to tree.    public TreeNode deserialize(String data) {        // base case        if(data.length() == 0) return null;        Queue
q = new LinkedList(); for(String s : data.split(",")) q.offer(Integer.valueOf(s)); return decode(q); } private TreeNode decode(Queue
q) { if(q.isEmpty()) return null; int cur = q.poll(); TreeNode root = new TreeNode(cur); Queue
left = new LinkedList(); while(!q.isEmpty() && q.peek() < cur) left.offer(q.poll()); root.left = decode(left); root.right = decode(q); return root; }

转载地址:http://xmtax.baihongyu.com/

你可能感兴趣的文章
使用Putty密钥认证机制远程登录Linux
查看>>
一不小心,老司机又翻车了
查看>>
理解思科IPS系统的traffic flow notifications
查看>>
【博客话题】技术人生之三界修炼
查看>>
Ext JS 6开发实例(三) :主界面设计
查看>>
Hyper-V 3中虚拟机CPU竞争机制
查看>>
【原创】Oracle RAC原理和安装
查看>>
东哥读书小记 之 《MacTalk人生元编程》
查看>>
《随机出题软件》&《随机分队软件》源码(Windows API)
查看>>
python 文件及文件夹操作
查看>>
Android自定义ListView的Item无法响应OnItemClick的解决办法
查看>>
Building Apps for Windows Phone 8.1教程下载地址整理
查看>>
移动Web—CSS为Retina屏幕替换更高质量的图片
查看>>
[Linux 性能检测工具]SAR
查看>>
JS 运行、复制、另存为 代码。
查看>>
一个经典编程面试题的“隐退”
查看>>
阿里公共DNS 正式发布了
查看>>
Java抓取网页数据(原网页+Javascript返回数据)
查看>>
[转载] 推荐的C++书籍以及阅读顺序
查看>>
EasyUI基础入门之Pagination(分页)
查看>>