LeetCode 297. Serialize and Deserialize Binary Tree(이차 트리의 정렬화 및 반정렬화)

원본 사이트 주소:https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
    1
   / \
  2   3
     / \
    4   5

as  "[1,2,3,null,null,4,5]"
, just the same as  how LeetCode OJ serializes a binary tree
. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
방법1: 깊이 우선 + 귀속.
/**
 * 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) {
        if (root==null) return "[]";
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(root.val);
        sb.append(",");
        sb.append(serialize(root.left));
        sb.append(",");
        sb.append(serialize(root.right));
        sb.append("]");
        // System.out.printf("serialize: %s
", sb.toString()); return sb.toString(); } private int pos; private TreeNode parse(String data) { if (data.charAt(pos) != '[') return null; pos ++; if (data.charAt(pos) == ']') { pos ++; return null; } int val = 0; boolean negative = false; if (data.charAt(pos) == '-') { negative = true; pos ++; } for(;pos='0' && data.charAt(pos)<='9'; pos ++) { val = val*10+data.charAt(pos)-'0'; } if (negative) val = -val; TreeNode node = new TreeNode(val); // System.out.printf("val=%d
", val); if (data.charAt(pos) != ',') return null; pos ++; node.left = parse(data); if (data.charAt(pos) != ',') return null; pos ++; node.right = parse(data); if (data.charAt(pos) != ']') return null; pos ++; return node; } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { pos = 0; return parse(data); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));

방법2: 광도 우선.
/**
 * 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) {
        if (root == null) return "null";
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        LinkedList list = new LinkedList<>();
        list.add(root.left);
        list.add(root.right);
        while (!list.isEmpty()) {
            TreeNode node = list.remove();
            sb.append(",");
            if (node == null) sb.append("null");
            else {
                sb.append(node.val);
                list.add(node.left);
                list.add(node.right);
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        int pos = 0;
        pos = parse(data, pos);
        TreeNode root = parsed;
        if (root == null) return null;
        LinkedList nodes = new LinkedList<>();
        nodes.add(root);
        do {
            TreeNode node = nodes.remove();
            pos = parse(data, pos);
            node.left = parsed;
            if (node.left != null) nodes.add(node.left);
            pos = parse(data, pos);
            node.right = parsed;
            if (node.right != null) nodes.add(node.right);
        } while (!nodes.isEmpty());
        return root;
    }
    
    private TreeNode parsed;
    private int parse(String data, int pos) {
        if (data.charAt(pos) == 'n') {
            pos += 4;
            if (pos= '0' && data.charAt(pos) <= '9'; pos ++) {
            val = val * 10 + data.charAt(pos) - '0';
        }
        if (pos

방법3: 넓이를 우선하고 층별로 서열화한다.
/**
 * 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) {
        StringBuilder sb = new StringBuilder();
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            if (sb.length()>0) sb.append(",");
            if (node == null) sb.append("#");
            else {
                sb.append(node.val);
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if ("#".equals(data)) return null;
        String[] vals = data.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        for(int i=1; i

좋은 웹페이지 즐겨찾기