## Title description

Please implement two functions to serialize and deserialize binary trees respectively

The serialization of a binary tree refers to saving a binary tree as a string in a certain format according to the result of a certain traversal method, so that the binary tree established in the memory can be persistently stored. Serialization can be modified based on the binary tree traversal method of pre-order, middle-order, post-order, and layer order. The result of serialization is a string. When serializing, an empty node (#) is represented by a certain symbol. Indicates the end of a node value (value!).

The deserialization of the binary tree refers to reconstructing the binary tree according to the serialized string result str obtained in a certain traversal sequence.

For example, we can serialize a binary tree with a root node of 1 to "1,", and then use our own function to parse the binary tree back

## Idea analysis

First of all serialize, serialize according to your own set rules, then it is very simple and recursive directly, but in order to facilitate the follow-up, you need to add a special segmentation symbol to the string.
Deserialize again. Recursive Dafa

## Code

``````/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {

int index = -1;
String Serialize(TreeNode root) {

if(root == null){

return "#";
}else{

return root.val+","+Serialize(root.left)+","+Serialize(root.right);
}
}
TreeNode Deserialize(String str) {

String[] strArray = str.split(",");
index ++;
if(index>=strArray.length) return null;
TreeNode node = null;
if(!strArray[index].equals("#")){

node = new TreeNode(Integer.parseInt(strArray[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
}
``````

### Guess you like

Origin blog.csdn.net/H1517043456/article/details/107592933
Recommended
Ranking
Daily