二叉树的序列化与反序列化

Posted Alice_yufeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的序列化与反序列化相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode 
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x)  val = x; 
 * 
*/

public class Codec 
    public String serialize(TreeNode root) 
        return rserialize(root, "");
    
  
    public TreeNode deserialize(String data) 
        String[] dataArray = data.split(",");
        List<String> dataList = new LinkedList<String>(Arrays.asList(dataArray));
        return rdeserialize(dataList);
    

    public String rserialize(TreeNode root, String str) 
        if (root == null) 
            str += "None,";
         else 
            str += str.valueOf(root.val) + ",";
            str = rserialize(root.left, str);
            str = rserialize(root.right, str);
        
        return str;
    
  
    public TreeNode rdeserialize(List<String> dataList) 
        if (dataList.get(0).equals("None")) 
            dataList.remove(0);
            return null;
        
  
        TreeNode root = new TreeNode(Integer.valueOf(dataList.get(0)));
        dataList.remove(0);
        root.left = rdeserialize(dataList);
        root.right = rdeserialize(dataList);
    
        return root;
    


// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));

以上是关于二叉树的序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] 树 - 二叉树的序列化与反序列化, leetcode 297

[JavaScript 刷题] 树 - 二叉树的序列化与反序列化, leetcode 297

LeetCode 297. 二叉树的序列化与反序列化(bfs,二叉树,Java)

297. 二叉树的序列化与反序列化(困难)

LeetCode(算法)- 297. 二叉树的序列化与反序列化

[Notes] 2020.6.16 每日一题 二叉树的序列化与反序列化