|
| 1 | +package binarySearchTree; |
| 2 | + |
| 3 | +import utility.TreeNode; |
| 4 | + |
| 5 | +/* |
| 6 | +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, |
| 7 | +or transmitted across a network connection link to be reconstructed later in the same or another computer environment. |
| 8 | +
|
| 9 | +Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. |
| 10 | +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. |
| 11 | +
|
| 12 | +The encoded string should be as compact as possible. |
| 13 | +
|
| 14 | +Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. |
| 15 | + * */ |
| 16 | + |
| 17 | +public class SerializeDeserializeBST |
| 18 | +{ |
| 19 | + // Encodes a tree to a single string. |
| 20 | + public String serialize( TreeNode root ) |
| 21 | + { |
| 22 | + // preorder |
| 23 | + StringBuilder sb = new StringBuilder(); |
| 24 | + serializedfs( root, sb ); |
| 25 | + return sb.toString(); |
| 26 | + } |
| 27 | + |
| 28 | + private void serializedfs( TreeNode root, StringBuilder sb ) |
| 29 | + { |
| 30 | + if ( root == null ) |
| 31 | + return; // no "null " |
| 32 | + sb.append( root.val ).append( " " ); |
| 33 | + serializedfs( root.left, sb ); |
| 34 | + serializedfs( root.right, sb ); |
| 35 | + } |
| 36 | + |
| 37 | + public TreeNode deserialize( String data ) |
| 38 | + { |
| 39 | + if ( data.length() == 0 ) |
| 40 | + return null; |
| 41 | + String[] list = data.split( " " ); |
| 42 | + TreeNode dummy = new TreeNode( 0 ); |
| 43 | + deserializedfs( list, 0, dummy, true, Integer.MIN_VALUE, Integer.MAX_VALUE ); |
| 44 | + return dummy.left; |
| 45 | + } |
| 46 | + |
| 47 | + private int deserializedfs( String[] list, int pos, TreeNode root, boolean isleft, int lower, int upper ) |
| 48 | + { |
| 49 | + if ( pos >= list.length ) |
| 50 | + return pos; |
| 51 | + |
| 52 | + int val = Integer.valueOf( list[pos] ); |
| 53 | + if ( val < lower || val > upper ) |
| 54 | + { |
| 55 | + return pos - 1; // have not used this pos, so minus one |
| 56 | + } |
| 57 | + TreeNode currNode = new TreeNode( val ); |
| 58 | + |
| 59 | + if ( isleft ) |
| 60 | + { |
| 61 | + root.left = currNode; |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + root.right = currNode; |
| 66 | + } |
| 67 | + |
| 68 | + pos = deserializedfs( list, ++pos, currNode, true, lower, val ); |
| 69 | + pos = deserializedfs( list, ++pos, currNode, false, val, upper ); |
| 70 | + return pos; |
| 71 | + } |
| 72 | +} |
0 commit comments