[leetcode]449. Serialize and Deserialize BST序列化与反序列化BST

时间:2022-06-27 17:29:01

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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

思路

To makes it the most compact possible,  since we just need the order the values were inserted, we do not need to account for null nodes in the string with "#" or "null".

Hence, the final string contains only the values and separators, which makes it the most compact possible.

1. 在encode时候,don't account for null nodes

2. 在decode时候,不再用queue来存整个treenode的信息,而是用大小为1的数组idx来track当前扫到哪一个node了, 用idx来拿到该node value值(即mock up a pass-by-address process)。通过BST的attribute (left < root < right)来build tree.

代码

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

     private void buildString(TreeNode root, StringBuilder sb) {
         if (root == null) return;
         sb.append(root.val).append(",");
         buildString(root.left, sb);
         buildString(root.right, sb);
     }

     // Decodes your encoded data to tree.
     public TreeNode deserialize(String data) {
         if(data.length() == 0) return null;
         // use idx to mockup a pass-by-address
         int[] idx = new int[]{0};
         return buildTree(data.split(","), idx, Integer.MIN_VALUE, Integer.MAX_VALUE);
     }

     private TreeNode buildTree(String[] strArr, int[] idx, int min, int max) {
         if (idx[0] == strArr.length) return null;
         int val = Integer.parseInt(strArr[idx[0]]);
         // Go back if out of boundary
         if (val < min || val > max) return null;
         TreeNode root = new TreeNode(val);
         // move to next address
         idx[0]++;
         // corresponding to encode pre-order
         root.left = buildTree(strArr, idx, min, val);
         root.right = buildTree(strArr, idx, val, max);
         return root;
     }
 }