1. 程式人生 > >LintCode——7. 二叉樹的序列化和反序列化

LintCode——7. 二叉樹的序列化和反序列化

package lintcode;

import ds.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Class Name  : SerializeBT_7
 * Describe    : empty
 * Create User : yoo
 * Create Date : 2018/1/27
 * Create Time : 19:05
 **/

public class SerializeBT_7 {

    public static String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if (root == null)
            return null;
        Deque<TreeNode> nodeDeque = new ArrayDeque<TreeNode>();
        nodeDeque.add(root);
        sb.append(root.val);
        while (!nodeDeque.isEmpty()) {
            TreeNode p = nodeDeque.pop();
            if (p.left != null) {
                nodeDeque.add(p.left);
                sb.append("," + p.left.val);
            } else {
                sb.append(",#");
            }
            if (p.right != null) {
                nodeDeque.add(p.right);
                sb.append("," + p.right.val);
            } else {
                sb.append(",#");
            }
        }

        String results = sb.toString();
        while (results.endsWith(",#,#"))
            results = results.substring(0, results.length() - 4);

        return "{" + results + "}";
    }


    public static TreeNode deserialize(String data) {
        if (data == null || data.trim().length() < 2)
            return null;
        data = data.substring(1, data.length() - 1);

        String[] datas = data.split(",");
        Deque<TreeNode> nodeDeque = new ArrayDeque<TreeNode>();
        TreeNode root = new TreeNode(Integer.valueOf(datas[0]));
        nodeDeque.add(root);
        int i = 1;
        while (i < datas.length) {
            TreeNode node = nodeDeque.pop();
            if (!datas[i].equals("#")) {
                node.left = new TreeNode(Integer.valueOf(datas[i]));
                nodeDeque.add(node.left);
            } else {
                node.left = null;
            }
            i++;
            if (!(i < datas.length))
                break;
            if (!datas[i].equals("#")) {
                node.right = new TreeNode(Integer.valueOf(datas[i]));
                nodeDeque.add(node.right);
            } else {
                node.right = null;
            }
            i++;
        }
        return root;
    }
}