449. Serialize and Deserialize BST

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.

题目含义:实现二叉树的序列化和反序列化算法

思路:按照先序顺序序列化,将每个值用逗号分隔,构造序列化结果

          反序列化时候按照逗号分割出数组,由于是先序,所以数组第一个位置的元素即为根节点,从后面找到第一个大于根节点值的节点mid,即为右子树节点,所以从left到mid-1即为左子树,从mid到right即为右子树

 1 public class Codec {
 2 
 3 // Encodes a tree to a single string.
 4     public String serialize(TreeNode root) {
 5         StringBuilder sb  = new StringBuilder();
 6         serializeDFS(root, sb); //preorder root - left - right
 7         return sb.toString();
 8     }
 9     
10     public void serializeDFS(TreeNode root, StringBuilder sb){
11         if(root == null) return;
12         sb.append(root.val).append(",");
13         serializeDFS(root.left, sb);
14         serializeDFS(root.right, sb);
15     }
16     // Decodes your encoded data to tree.
17     public TreeNode deserialize(String data) {
18         if(data == null || data.length() == 0) return null;
19         String arr[] = data.split(",");
20         return deserializeDFS(arr, 0, arr.length-1);
21     }
22     
23     public TreeNode deserializeDFS(String[] array, int left, int right){
24         if(left > right || left >= array.length) return null;
25         TreeNode root = new TreeNode(Integer.parseInt(array[left]));
26         int mid = getNextGreater(array, left, right);
27         root.left = deserializeDFS(array, left + 1, mid - 1);
28         root.right = deserializeDFS(array, mid, right);
29         return root;
30     }
31     
32     public int getNextGreater(String[] array, int left, int right){
33         int index = 0;
34         System.out.println(left);
35         int init = Integer.parseInt(array[left]);
36         while(left <= right){
37             if(init < Integer.parseInt(array[left])) {
38                 break;
39             }
40             else left++;
41         }
42         return left;
43     }
44 }
45 
46 // Your Codec object will be instantiated and called as such:
47 // Codec codec = new Codec();
48 // codec.deserialize(codec.serialize(root));
原文地址:https://www.cnblogs.com/wzj4858/p/7712014.html