码迷,mamicode.com
首页 > 其他好文 > 详细

37. 序列化二叉树

时间:2020-04-03 22:09:27      阅读:66      评论:0      收藏:0      [点我收藏+]

标签: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;
        
    }
    
}

 

 

37. 序列化二叉树

标签:div   tools   ble   lse   value   面试题   equal   enc   serialize   

原文地址:https://www.cnblogs.com/zzytxl/p/12628996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!