Offer to prove safety sixty-one: sequence of binary tree

Casual working

Implement two functions are used to serialize and deserialize binary
sequence of binary tree means: traversing the binary tree according to some embodiment of the result is saved in a format for the string, so that the build up memory binary tree can persist. 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

First traversal time for storage, and then recover to become a binary tree traversal according to the same rules. It seems like nothing can be that way.

Code

public class Solution {
   
      
    String Serialize(TreeNode root) {
        if(root == null)
            return "";
        StringBuilder sb = new StringBuilder();
        Serialize2(root, sb);
        return sb.toString();
    }
     
    void Serialize2(TreeNode root, StringBuilder sb) {
        if(root == null) {
            sb.append("#,");
            return;
        }
        sb.append(root.val);
        sb.append(',');
        Serialize2(root.left, sb);
        Serialize2(root.right, sb);
    }
     
    int index = -1;
     
    TreeNode Deserialize(String str) {
        if(str.length() == 0)
            return null;
        String[] strs = str.split(",");
        return Deserialize2(strs);
    }  
     
    TreeNode Deserialize2(String[] strs) {
        index++;
        if(!strs[index].equals("#")) {
            TreeNode root = new TreeNode(0);     
            root.val = Integer.parseInt(strs[index]);
            root.left = Deserialize2(strs);
            root.right = Deserialize2(strs);
            return root;
        }
        return null;
    }
       
  }
Published 84 original articles · won praise 53 · views 7383

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105422533