严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

SerializeDesrializeTree

Go down

SerializeDesrializeTree Empty SerializeDesrializeTree

Post by Admin Sat Oct 21, 2017 2:35 pm

public String serialize(BTreeNode root) {
     if(root==null)
         return "";         
     StringBuilder sb = new StringBuilder();
     Queue<BTreeNode> queue = new LinkedList<BTreeNode>();
     queue.offer(root);      
     while(!queue.isEmpty()){
     BTreeNode curNode = queue.poll();
         if(curNode==null){
         sb.append("#,");
         }else{
             sb.append(String.valueOf(curNode.val) + ",");
             queue.offer(curNode.left);
             queue.offer(curNode.right);
         }
     }
     sb.deleteCharAt(sb.length()-1); 
     return sb.toString();
 }

 public BTreeNode deserialize(String data){
     if(data==null || data.length()==0)
         return null;   
     String[] nodeValues = data.split(",");
     BTreeNode root = new BTreeNode(Integer.parseInt(nodeValues[0]));     
     Queue<BTreeNode> queue = new LinkedList<BTreeNode>();
     queue.offer(root);   
     int i=1;      
     while(!queue.isEmpty()){
     BTreeNode curNode = queue.poll();   
         if(curNode==null)
         continue;          
         if(!nodeValues[i].equals("#")){
         curNode.left = new BTreeNode(Integer.parseInt(nodeValues[i]));    
             queue.offer(curNode.left);   
         }else{
         curNode.left = null;
             queue.offer(null);
         }
         i++;          
         if(!nodeValues[i].equals("#")){
         curNode.right = new BTreeNode(Integer.parseInt(nodeValues[i]));    
             queue.offer(curNode.right);   
         }else{
         curNode.right = null;
             queue.offer(null);
         }
         i++;          
     }
     return root;
 }
 
 
public static void main(String[] args) {
// TODO Auto-generated method stub
SerializeDesrializeTree test=new SerializeDesrializeTree();
BTreeNode root = new BTreeNode(1);
   root.left = new BTreeNode(2);
        root.right = new BTreeNode(3);
        root.right.left = new BTreeNode(4);
        root.right.right = new BTreeNode(5);
        root.right.left.left=new BTreeNode(6);
        root.right.left.right=new BTreeNode(7);
        root.right.right.left = new BTreeNode(Cool;
        root.right.right.right = new BTreeNode(9);
        BTreePrinter.printNode(root);
        String res=test.serialize(root);
        System.out.println(res);
        String serial="1,2,3,#,#,4,5,6,7,8,9,#,#,#,#,#,#,#,#";
        BTreeNode deserial=test.deserialize(serial);
        BTreePrinter.printNode(deserial);
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum