1. 程式人生 > >[leetcode]449. Serialize and Deserialize BST序列化反序列化二叉搜尋樹(儘量緊湊)

[leetcode]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.

 

題目

序列化反序列化二叉搜尋樹(儘量緊湊)

 

思路

這個題最大不同是 “encoded string needs to be as compact as possible”. 即encode儘量緊湊

那麼我們做的一個優化是,

在encode的時候,不再將root == null的資訊encode到string裡

問題來了,在decode的時候,怎麼讀取root == null的結點資訊呢?

用int[] idx = new int[]{0}去track當前處理的是String[] nodes 中的第幾個node 

利用BST的attribute

若 such node value < min || > max, 肯定越界,返null

 

程式碼

 1 public class Codec {
 2     // Encodes a tree to a single string.
 3     public String serialize(TreeNode root) {
 4         StringBuilder sb = new StringBuilder();
 5         buildString(root, sb);
 6         return
sb.toString(); 7 } 8 9 private void buildString(TreeNode root, StringBuilder sb) { 10 if (root == null) return; 11 /*Q: 為何不將 root == null 加到stringbuilder裡? 12 Since we just need the order the values were inserted, you do not need to account for null nodes in the string with "#" or "null". Hence, the final string contains only the values and 13 separators, which makes it the most compact possible. 14 Q: 為何選擇pre-order 15 preorder traversal 的時候, 對於當前節點,所有的左節點比他小,右節點比他大 16 */ 17 sb.append(root.val).append(","); 18 buildString(root.left, sb); 19 buildString(root.right, sb); 20 } 21 22 // Decodes your encoded data to tree. 23 public TreeNode deserialize(String data) { 24 if (data.length() == 0) return null; 25 // 26 int[] idx = new int[]{0}; 27 idx[0] = 0; 28 return buildTree(data.split(","), idx, Integer.MIN_VALUE, Integer.MAX_VALUE); 29 } 30 31 private TreeNode buildTree(String[] nodes, int[] idx, int min, int max) { 32 if (idx[0] == nodes.length) return null; 33 int val = Integer.parseInt(nodes[idx[0]]); 34 if (val < min || val > max) return null; // Go back if we are over the boundary 35 TreeNode cur = new TreeNode(val); 36 idx[0]++; // update current position 37 /*keep with encode pre-order*/ 38 cur.left = buildTree(nodes, idx, min, val); 39 cur.right = buildTree(nodes, idx, val, max); 40 return cur; 41 } 42 }