Advertisement
Kuroshi1

Untitled

Aug 31st, 2022
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. public class Codec {
  2.     // Encodes a tree to a single string.
  3.     public String serialize(TreeNode root) {
  4.         test = root;
  5.         String result = "[";
  6.         if (root == null) return result + "]";
  7.        
  8.         Queue<TreeNode> q = new LinkedList<>();
  9.        
  10.         q.add(root);
  11.        
  12.         while (!q.isEmpty()) {
  13.             int preSize = q.size();
  14.            
  15.             for (int i = 0; i < preSize; i++) {
  16.                 TreeNode curr = q.poll();
  17.                 if (curr == null) {
  18.                     result += "null,";
  19.                 } else {
  20.                     result += curr.val + ",";
  21.                     q.add(curr.left);
  22.                     q.add(curr.right);
  23.                 }
  24.             }
  25.         }
  26.        
  27.         int firstIdx = result.length() - 5;
  28.         while (result.substring(firstIdx, result.length()).equals("null,")) {
  29.             firstIdx -= 5;
  30.         }
  31.         return result.substring(0, firstIdx - 1) + "]";
  32.     }
  33.    
  34.     //[1,2,null,null,
  35.     // Decodes your encoded data to tree.
  36.     public TreeNode deserialize(String data) {
  37.         return test;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement