coder 进阶的专栏


[LeetCode 297] 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

   / \
  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. preorder traversal, use another helper class(StringToken) to split string, and record current position

2. level order traversal

public class Codec {

 // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        helptoserialize(root, sb);
        return sb.toString();

    public void helptoserialize(TreeNode root, StringBuilder sb) {
        if(root == null) {
            sb.append("# ");
        } else {
            sb.append(" ");
            helptoserialize(root.left, sb);
            helptoserialize(root.right, sb);

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        TreeNode root = helptodeserialize(new StringToken(data, " "));
        return root;
    public TreeNode helptodeserialize(StringToken token) {
        if(!token.hasMoreElement()) return null;
        String t1 = token.nextElement();
        if(t1.equals("#")) return null;
        TreeNode root = new TreeNode(Integer.valueOf(t1));
        root.left = helptodeserialize(token);
        root.right = helptodeserialize(token);
        return root;

    class StringToken {
        public int len = 0;
        ArrayList<String> dataStrings = new ArrayList<>();
        public StringToken (String data, String spliter) {
            String[] datas = data.split(spliter);
            for(int i=0;i<datas.length;i++) {
        public boolean hasMoreElement() {
            return len<dataStrings.size();
        public String nextElement() {
            return dataStrings.get(len++);

个人分类: Java Leetcode
想对作者说点什么? 我来说一句



[LeetCode 297] Serialize and Deserialize Binary Tree