剑指 Offer 37. 序列化二叉树

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树。

解题思路

public class Codec {
   // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "[]";
        ArrayList levelTraversalHelper = new ArrayList<>();
        ArrayList levelTraversalResult = new ArrayList<>();
        final StringBuilder sb = new StringBuilder();
        sb.append("[");
        levelTraversalHelper.add(root);
        while (!levelTraversalHelper.isEmpty()) {
            final TreeNode treeNode = levelTraversalHelper.remove(0);
            if (treeNode != null) {
                levelTraversalResult.add(treeNode.val);
                levelTraversalHelper.add(treeNode.left);
                levelTraversalHelper.add(treeNode.right);
                continue;
            }
            levelTraversalResult.add(null);
        }

        // [1,2,3,null,null,4,5,null.null,null,null] -> [1,2,3,null,null,4,5]
        while (levelTraversalResult.get(levelTraversalResult.size() - 1) == null) {
            levelTraversalResult.remove(levelTraversalResult.size() - 1);
        }

        for (Integer i : levelTraversalResult) {
            if (i != null) {
                sb.append(i).append(",");
                continue;
            }
            sb.append("null,");
        }

        sb.deleteCharAt(sb.length() - 1);
        sb.append("]");

        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == "[]") return null;
        final String[] values = data.substring(1, data.length() - 1).split(",");
        final ArrayList queue = new ArrayList<>();
        queue.add(new TreeNode(Integer.parseInt(values[0])));
        boolean isLeftNode = true;
        int index = 0;

        for (int i = 1; i < values.length; i++) {
            if (!"null".equals(values[i])) {
                final TreeNode node = new TreeNode(Integer.parseInt(values[i]));
                if (isLeftNode) {
                    queue.get(index).left = node;
                } else {
                    queue.get(index).right = node;
                }
                queue.add(node);
            }
            if (!isLeftNode) index++;
            isLeftNode = !isLeftNode;
        }

        return queue.get(0);
    }
}

你可能感兴趣的:(剑指 Offer 37. 序列化二叉树)