左神算法——第16题——二叉树的序列化和反序列化

在这里插入图片描述

//请实现两个函数,分别用来序列化和反序列化二叉树
import java.util.LinkedList;
import java.util.Queue;

public class e03Serialize {
    public static class TreeNode{
        int val=0;
        TreeNode left=null;
        TreeNode right=null;
        public TreeNode(int val){
            this.val=val;
        }
    }
    //序列化
    public static String Serialize(TreeNode root){
        if(root==null){
            return "#!";
        }
        String res=root.val+"!";
        res+=Serialize(root.left);
        res+=Serialize(root.right);
        return res;
    }
    //反序列化
    public static TreeNode Deserialize(String str){
        if(str==null||str.trim().equals("")){
            return null;
        }
        String[] strs=str.split("!");
        return reconPreOrder(strs);
    }
    static int index=0;
    public static TreeNode reconPreOrder(String[] chars){
        if(index >= chars.length||chars[index].equals("#")){
            index++;
            return null;
        }
        TreeNode node=new TreeNode(Integer.valueOf(chars[index++]));
        node.left=reconPreOrder(chars);
        node.right=reconPreOrder(chars);
        return node;
    }


    //序列化2
    public static String Serialize2(TreeNode root) {
        if (root == null) {
            return "#!";
        }
        String res = root.val + "!";
        res += Serialize(root.left);
        res += Serialize(root.right);
        return res;
    }

    //反序列化2
    public static TreeNode Deserialize2(String str) {
        if(str==null||str.trim().equals("")){
            return null;
        }
        String[] values = str.split("!");
        Queue<String> queue = new LinkedList<>();
        for (int i = 0; i != values.length; i++) {
            queue.offer(values[i]);
        }
        return reconPreOrder2(queue);
    }
    public static TreeNode reconPreOrder2(Queue<String> queue) {
        String value = queue.poll();
        if (value.equals("#")) {
            return null;
        }
        TreeNode head = new TreeNode(Integer.valueOf(value));
        head.left = reconPreOrder2(queue);
        head.right = reconPreOrder2(queue);
        return head;
    }
}

你可能感兴趣的:(左神算法)