Binary Serialization - offer to prove safety

Title Description

Implement two functions are used to serialize and deserialize binary
 
It refers to a sequence of binary: the binary tree is saved in a format string in accordance with the result of a traversing manner such that the memory can be set up binary persisted. Serialization may be based on the first order, in sequence, after, the binary tree traversal sequence is modified, the sequence of the result is a string representing the blank nodes (#) by some sequences of symbol to! End node represents a value (value!).

Deserialized binary tree means: The serialized string str some results obtained traversal order to reconstruct a binary tree.
 
Thinking: preorder traversal is then stored in a string from the string constructed
Two recursive
public class Solution {
    int i=-1;
    String Serialize(TreeNode root) {
        StringBuilder sb=new StringBuilder();
        if(root == null) return "#!";
        SerializeHelper(root,sb);
        return sb.toString();
    }

    /*
    前序遍历
     */
    private void SerializeHelper(TreeNode root, StringBuilder sb) {
        if(root == null){
            sb.append("#!");
            return;
        }
        sb.append(String.valueOf(root.val));
        sb.append("!");
        SerializeHelper(root.left,sb);
        SerializeHelper(root.right,sb);
    }

    TreeNode Deserialize(String str) {
        if (str == null) return null;
        String[] strings=str.split("!");
        if(strings.length == 1) return null;
        return DeserializeHelper(strings);
    }

    private TreeNode DeserializeHelper(String[] str) {
        TreeNode root=null;
        i ++;
        if(!str[i].equals("#")) {
            root = new TreeNode(Integer.valueOf(str[i]));
            root.left = DeserializeHelper(str);
            root.right = DeserializeHelper(str);
        }
        return root;
    }
}

 

Guess you like

Origin www.cnblogs.com/nlw-blog/p/12482197.html