二叉树序列化和反序列化

public class BinaryTreeSerialize {

    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.right.left = new Node(8);
        root.left.right.right = new Node(9);

        //序列化二叉树, null用#表示,每个节点之间用_分隔
        String str = serialize(root);
        System.out.println(str);
        
        //反序列化
        Node node = deserialize(str);
        
        //验证反序列 的结果对不对
        System.out.println(serialize(node));

    }

    
    public static Node deserialize(String str) {
        String[] split = str.split("_");
        Queue<String> queue = new LinkedList<>();
        for (String s : split) {
            queue.offer(s);
        }
        return setp(queue);
    }

    
    public static Node setp(Queue<String> queue) {
            String str = queue.poll();
            if (str.equals("#")) {
                return null;
            }
            Node root = new Node(Integer.parseInt(str));
            root.left = setp(queue);
            root.right = setp(queue);
            return root;
    }

    
    public static String serialize(Node root) {
        if (root == null) {
            return "#_";
        }
        String selfStr = root.value + "_";
        String leftStr = serialize(root.left);
        String rightStr = serialize(root.right);
        return selfStr + leftStr + rightStr;
    }

    public static class Node {
        Node left;
        Node right;
        int value;

        public Node(int value) {
            this.value = value;
        }

    }
}
原文地址:https://www.cnblogs.com/moris5013/p/11660793.html