标签:div tools ble lse value 面试题 equal enc serialize
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
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; } }
标签:div tools ble lse value 面试题 equal enc serialize
原文地址:https://www.cnblogs.com/zzytxl/p/12628996.html