Friday, October 6, 2017

297. Serialize and Deserialize Binary Tree

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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
    1
   / \
  2   3
     / \
    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Solution:
Serialize: 
Binary tree level order, use "#" for null treenode, use "," to separate each node.
Deserialize:
Use a queue to track the processed nodes, the head of the queue will be the parent of current processed nodes. Except the root node, all nodes should be perfectly paired with left and right nodes in order.
 public class Codec {  
   // Encodes a tree to a single string.  
   public String serialize(TreeNode root) {  
     if(root==null) return null;  
     StringBuilder sb=new StringBuilder();  
     LinkedList<TreeNode> q=new LinkedList<TreeNode>();  
     q.offer(root);  
     while(!q.isEmpty()){  
       TreeNode cur=q.poll();  
       if(cur==null) sb.append("#");  
       else sb.append(cur.val);  
       sb.append(",");  
       if(cur!=null){  
         q.offer(cur.left);  
         q.offer(cur.right);  
       }  
     }  
     return sb.toString();  
   }  
   // Decodes your encoded data to tree.  
   public TreeNode deserialize(String data) {  
     if(data==null) return null;  
     String[] vals=data.split(",");  
     TreeNode head=new TreeNode(Integer.parseInt(vals[0]));  
     LinkedList<TreeNode> q=new LinkedList<TreeNode>();  
     q.offer(head);  
     for(int i=1;i<vals.length;i=i+2){  
       TreeNode l=vals[i].equals("#")? null : new TreeNode(Integer.parseInt(vals[i]));  
       TreeNode r=vals[i+1].equals("#")? null : new TreeNode(Integer.parseInt(vals[i+1]));  
       TreeNode par=q.poll();  
       par.left=l;  
       par.right=r;  
       if(l!=null) q.offer(l);  
       if(r!=null) q.offer(r);  
     }  
     return head;      
   }  
 }  

No comments:

Post a Comment