LintCode 7.Serialize and Deserialize Binary Tree (with test code)

Keywords: Java Programming

Title Description

Design an algorithm and write code to serialize and deserialize binary trees. Writing a tree into a file is called serialization, and rebuilding the same binary tree after reading the file is called deserialization.

There is no limit to how to deserialize or serialize a binary tree. You just need to make sure that the binary tree can be serialized into a string and that the string can be deserialized into the original tree structure.

Example

Given a sample test data, the binary tree {3,9,20,#,#, 15,7} represents the following tree structure:

Our data is obtained by BFS traversal. When you test the result wrong answer, you can debug your code as input. You can serialize and deserialize in other ways.

 

In the process of programming, Queue queue structure is used to save tree nodes, so it is necessary to familiarize ourselves with the knowledge points of Queue interface (Deque interface is a sub-interface of Queue interface, representing a double-ended queue).

1.Queue interface belongs to the same level as List and Set and inherits Collection interface. The LinkedList class implements the Queue interface, so we can use LinkedList as Queue.

2. When using Queue, try to avoid the add() and remove() methods of Collection, but use offer() to add elements and poll() to get and remove elements. Their advantage is that they can determine success by returning values, while add() and remove() methods throw exceptions when they fail.

 

In addition, to use string structure, we need to understand the difference between String, String Builder and String Buffer.

1. First of all, the running speed, or execution speed, is: StringBuilder > StringBuffer > String.

The slowest reason for String is:

String is a string constant, while StringBuilder and StringBuffer are both string variables, that is, once a String object is created, the object is immutable, but the objects of the latter two are variables and can be changed.

2. Thread Safety

In thread security, StringBuilder is thread-insecure, while StringBuffer is thread-safe.

So:
String: For a small number of string operations

StringBuilder: Suitable for large number of operations in character buffer under single thread

StringBuffer: Suitable for large number of operations in character buffer under multithreading

 

Implementation code:

  1 import java.util.LinkedList;
  2 import java.util.Queue;
  3 
  4 class TreeNode {
  5     public int val;//Node value
  6     public TreeNode left,right;//Left and right nodes
  7     public TreeNode(int val){
  8         this.val = val;//Initialization node
  9         this.left = this.right = null;
 10     }
 11 }
 12 
 13 public class SerializeTree {
 14     public static void main(String[] args) throws Exception {
 15         TreeNode node1 = new TreeNode(3);
 16         TreeNode node2 = new TreeNode(9);
 17         TreeNode node3 = new TreeNode(20);
 18         node1.left = node2;
 19         node1.right = node3;
 20         TreeNode node4 = new TreeNode(15);
 21         TreeNode node5 = new TreeNode(7);
 22         node3.left = node4;
 23         node3.right = node5;
 24         
 25         String s = new SerializeTree().serialize(node1);
 26         System.out.println(s);
 27         
 28         String str = new String("3,9,20,#,#,15,7");
 29         //TreeNode root = new SerializeTree().deserialize(s);
 30         TreeNode root = new SerializeTree().deserialize(str);
 31         System.out.println((int)root.val);
 32         System.out.println(root.left.val);
 33         System.out.println(root.right.val);
 34         
 35         
 36     }
 37     
 38     /*Serialize a tree into a string*/
 39     public String serialize(TreeNode root) {
 40         Queue<TreeNode> queue = new LinkedList<>();
 41         StringBuffer sb = new StringBuffer();
 42         
 43         queue.offer(root);
 44         while(!queue.isEmpty()) {
 45             TreeNode data = queue.poll();
 46             if(data != null) {
 47                 sb.append(data.val+",");
 48                 queue.offer(data.left);
 49                 queue.offer(data.right);
 50             }
 51             else
 52                 sb.append("#,");
 53         }
 54         //return sb.toString();
 55         return sb.substring(0, sb.length()-1);//Remove the "," sign at the end of the string
 56     }
 57     
 58     /*Deserialize a string into a tree*/
 59     public TreeNode deserialize(String data) throws Exception {
 60         Queue<TreeNode> queue = new LinkedList<>();
 61         String string = data.substring(0, data.length());
 62         String[] s = string.split(",");
 63         /*for(int i =0;i<s.length-1;i++) {
 64             System.out.print(s[i]+" ");
 65         }
 66         System.out.println(s[s.length-1]);*/
 67         int i = 0;
 68         if(s[i].equals("#")) 
 69             return null;
 70         
 71         TreeNode root = new TreeNode(Integer.parseInt(s[i]));
 72         queue.offer(root);
 73         
 74         while(!queue.isEmpty() && i < s.length-1 )  {
 75             i++;
 76             TreeNode tmp = queue.poll();
 77             
 78                 if(s[i].equals("#")) {
 79                     
 80                     tmp.left = null;
 81                 }
 82             else
 83             {
 84                 TreeNode left = new TreeNode(Integer.parseInt(s[i]));
 85                 tmp.left = left;
 86                 queue.offer(left);
 87             }
 88             
 89             i++;
 90             if(s[i].equals("#"))
 91                 tmp.right = null;
 92             else 
 93             {
 94                 TreeNode right = new TreeNode(Integer.parseInt(s[i]));
 95                 tmp.right = right;
 96                 queue.offer(right);
 97             }
 98         }
 99         return root;
100     }
101         
102 }

 

 

 

 

Posted by Thierry on Tue, 11 Dec 2018 10:57:05 -0800