[The sword refers to the offer brushing the question] AcWing 50. Serialize the binary tree

Thought

recursion, search

topic

Please implement two functions to serialize and deserialize binary trees respectively.

You need to make sure that the binary tree can be serialized to a string, and that this string can be deserialized to the original tree structure.
data range

Number of nodes in tree [0,1000]

.
Sample

You can serialize a binary tree like
8
/
12 2
/
6 4

为:"[8, 12, 2, null, null, 6, 4, null, null, null, null]"

Notice:

以上的格式是AcWing序列化二叉树的方式,你不必一定按照此格式,所以可以设计出一些新的构造方式。

java code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    

    int index = -1;
    // Encodes a tree to a single string.
    String serialize(TreeNode root) {
    
    
        StringBuilder sb = new StringBuilder();
        if(root==null) {
    
    
            sb.append("null,");
            return sb.toString();
        }

        sb.append(root.val).append(",");
        sb.append(serialize(root.left));
        sb.append(serialize(root.right));
        
        // System.out.println(sb.toString());
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    TreeNode deserialize(String data) {
    
    
        index++;
        String[] nodes = data.split(",");
        
        // for (int i = 0; i < nodes.length; i++) {
    
    
        //     System.out.println(nodes[i]);
        // }
        
        TreeNode node = null;
        if(!nodes[index].equals("null")){
    
    
            node = new TreeNode(Integer.valueOf(nodes[index]));
            node.left = deserialize(data);
            node.right = deserialize(data);
        }
        return node;

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326189731&siteId=291194637