Advertisement
Kuroshi1

Untitled

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