37. 序列化二叉树
Posted zzytxl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了37. 序列化二叉树相关的知识,希望对你有一定的参考价值。
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ 2 3
/ 4 5
序列化为 "[1,2,3,null,null,4,5]"
/** * 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) { return serialize(root,""); } private String serialize(TreeNode root,String sb){ if(root == null){ sb += "null,"; }else{ sb += root.val + ","; sb = serialize(root.left,sb); sb = serialize(root.right,sb); } return sb; } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] strs = data.split(","); List<String> list = new LinkedList<>(Arrays.asList(strs)); return deserialize(list); } private TreeNode deserialize(List<String> list){ if(list.get(0).equals("null")){ list.remove(0); return null; } TreeNode root = new TreeNode(Integer.valueOf(list.get(0))); list.remove(0); root.left = deserialize(list); root.right = deserialize(list); return root; } }
以上是关于37. 序列化二叉树的主要内容,如果未能解决你的问题,请参考以下文章