LeetCode 449. Serialize and Deserialize BST

原题链接在这里:https://leetcode.com/problems/serialize-and-deserialize-bst/description/

题目:

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.

题解:

Serialize and Deserialize Binary Tree相同解法.

Time Complexity: serialize, O(n). deserialize, O(n). Space: O(n).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Codec {
11 
12     // Encodes a tree to a single string.
13     public String serialize(TreeNode root) {
14         StringBuilder sb = new StringBuilder();
15         preorder(root, sb);
16         return sb.toString();
17     }
18     
19     private void preorder(TreeNode root, StringBuilder sb){
20         if(root == null){
21             sb.append("#").append(",");
22             return;
23         }
24         sb.append(root.val).append(",");
25         preorder(root.left, sb);
26         preorder(root.right, sb);
27     }
28 
29     // Decodes your encoded data to tree.
30     public TreeNode deserialize(String data) {
31         LinkedList<String> que = new LinkedList<String>();
32         que.addAll(Arrays.asList(data.split(",")));
33         return deserial(que);
34     }
35     
36     private TreeNode deserial(LinkedList<String> que){
37         String str = que.pollFirst();
38         if(str.equals("#")){
39             return null;
40         }
41         TreeNode root = new TreeNode(Integer.valueOf(str));
42         root.left = deserial(que);
43         root.right = deserial(que);
44         return root;
45     }
46 }
47 
48 // Your Codec object will be instantiated and called as such:
49 // Codec codec = new Codec();
50 // codec.deserialize(codec.serialize(root));

 

posted @ 2018-01-25 15:51  Dylan_Java_NYC  阅读(690)  评论(0编辑  收藏  举报