面试题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; } }
原文地址:https://www.cnblogs.com/zzytxl/p/12628996.html
时间: 2024-11-08 06:20:04