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

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

题目:

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   5as "[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.

分析:利用层次遍历进行序列化,在反序列化时,TreeNode数组中每个节点的left节点下标为2*(i-nullNum)+1,right节点下标为2*(i-nullNum)+2,其中nullNum为TreeNode数组中元素null的个数。

Java代码及注释如下:

// Encodes a tree to a single string.    public String serialize(TreeNode root) {      // 1,2,3,null,null,4,5,null,null,null,null        if (root == null) {            return "";        }        StringBuilder sb = new StringBuilder();        Queue
queue = new LinkedList
(); queue.offer(root); while (! queue.isEmpty()) { //利用队列进行层次遍历(广搜) TreeNode tmp = queue.poll(); if (tmp != null) { sb.append(tmp.val); queue.offer(tmp.left); queue.offer(tmp.right); } else { sb.append("null"); } sb.append(","); } sb.deleteCharAt(sb.length()-1); return sb.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if ("".equals(data)) { return null; } String[] tmp = data.split(","); TreeNode[] node = new TreeNode[tmp.length]; // 根据序列化数组元素构造TreeNode数组. for (int i = 0; i < node.length; i++) { if ("null".equals(tmp[i])) { node[i] = null; } else { node[i] = new TreeNode(Integer.parseInt(tmp[i])); } } int nullNum = 0; for (int i = 0; i < tmp.length; i++) { //找到TreeNode数组中每个node所指向的left和right节点。 if (node[i] != null) { node[i].left = node[2*(i-nullNum)+1]; node[i].right = node[2*(i-nullNum)+2]; } else { nullNum++; } } return node[0]; //返回root }

 

转载于:https://www.cnblogs.com/lasclocker/p/4927842.html

你可能感兴趣的文章
VS+QT中文乱码问题
查看>>
FPGA开发全攻略——综合
查看>>
Idea Request method 'HEAD' not supported
查看>>
函数模板
查看>>
C#压缩文件为zip格式
查看>>
HDU 3861 The King’s Problem(tarjan连通图与二分图最小路径覆盖)
查看>>
媒体播放器三大底层架构
查看>>
如何在win10+vs2013上配置MPI并行编程环境
查看>>
Python学习第二十一节(继承顺序,super)
查看>>
KH4 删除字典数据
查看>>
socket.io,远程控制你的幻灯片
查看>>
Android窃取用户信息新思路
查看>>
leetcode 8. String to Integer (atoi)
查看>>
快速笔记02-MySQL主从复制原理半同步操作步骤及原理
查看>>
water mark
查看>>
文件属性的设置
查看>>
C# using 用法
查看>>
网易2018校园招聘编程题真题集合之重排序列
查看>>
php导出excel
查看>>
xml中报错,验证是否是xml报错
查看>>