LeetCode - Hard - 297. Serialize and Deserialize Binary Tree

怼烎@ 2022-10-08 11:21 71阅读 0赞

Topic

  • Tree
  • Design

Description

https://leetcode.com/problems/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.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Example 1:
9387977615b7e602406be82d7d4452b9.png

  1. Input: root = [1,2,3,null,null,4,5]
  2. Output: [1,2,3,null,null,4,5]

Example 2:

  1. Input: root = []
  2. Output: []

Example 3:

  1. Input: root = [1]
  2. Output: [1]

Example 4:

  1. Input: root = [1,2]
  2. Output: [1,2]

Constraints:

  • The number of nodes in the tree is in the range [ 0 , 1 0 4 ] [0, 10^4] [0,104].
  • − 1000 < = N o d e . v a l < = 1000 -1000 <= Node.val <= 1000 −1000<=Node.val<=1000

Analysis

方法一:自己写的,BFS

方法二:别人写的,前序遍历模式

方法三:别人写的,BFS

Submission

  1. import java.util.Arrays;
  2. import java.util.Deque;
  3. import java.util.LinkedList;
  4. import java.util.Queue;
  5. import com.lun.util.BinaryTree.TreeNode;
  6. public class SerializeAndDeserializeBinaryTree {
  7. //方法一:自己写的,BFS
  8. public static class Codec {
  9. // Encodes a tree to a single string.
  10. public String serialize(TreeNode root) {
  11. if(root == null) return "";
  12. StringBuilder sb = new StringBuilder();
  13. LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
  14. queue.offer(root);
  15. int maxDepth = maxDepth(root);
  16. int currentDepth = 0;
  17. while(!queue.isEmpty()) {
  18. currentDepth++;
  19. for(int size = queue.size(); size > 0; size--) {
  20. TreeNode node = queue.poll();
  21. sb.append(node != null ? node.val : "N");
  22. sb.append(',');
  23. if(node != null && currentDepth != maxDepth) {
  24. queue.offer(node.left);
  25. queue.offer(node.right);
  26. }
  27. }
  28. }
  29. return sb.substring(0, sb.length() - 1);
  30. }
  31. private int maxDepth(TreeNode node) {
  32. if(node == null) return 0;
  33. return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
  34. }
  35. // Decodes your encoded data to tree.
  36. public TreeNode deserialize(String data) {
  37. if(data == null || data.strip().isEmpty())
  38. return null;
  39. TreeNode root = null, parent = null;
  40. boolean pollFlag = true, sign = false;
  41. Integer value = null;
  42. LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
  43. for(int i = 0; i <= data.length(); i++) {
  44. if(i == data.length() || data.charAt(i) == ',') {
  45. TreeNode node = null;
  46. if(value != null) {
  47. node = new TreeNode(value * (sign ? -1 : 1));
  48. if(root == null) {
  49. root = node;
  50. queue.offer(root);
  51. value = null;
  52. continue;
  53. }
  54. }
  55. if(pollFlag) {
  56. parent = queue.poll();
  57. if(value != null) {
  58. parent.left = node;
  59. queue.offer(node);
  60. }
  61. }else {
  62. if(value != null) {
  63. parent.right = node;
  64. queue.offer(node);
  65. }
  66. }
  67. pollFlag = !pollFlag;
  68. value = null;
  69. sign = false;
  70. }else {
  71. if(data.charAt(i) != 'N') {
  72. if(data.charAt(i) == '-') {
  73. sign = true;
  74. continue;
  75. }
  76. if(value == null) value = 0;
  77. value = value * 10 + data.charAt(i) - '0';
  78. }
  79. }
  80. }
  81. return root;
  82. }
  83. }
  84. //方法二:别人写的,前序遍历模式
  85. public static class Codec2 {
  86. private static final String spliter = ",";
  87. private static final String NN = "X";
  88. // Encodes a tree to a single string.
  89. public String serialize(TreeNode root) {
  90. StringBuilder sb = new StringBuilder();
  91. buildString(root, sb);
  92. return sb.toString();
  93. }
  94. private void buildString(TreeNode node, StringBuilder sb) {
  95. if (node == null) {
  96. sb.append(NN).append(spliter);
  97. } else {
  98. sb.append(node.val).append(spliter);
  99. buildString(node.left, sb);
  100. buildString(node.right,sb);
  101. }
  102. }
  103. // Decodes your encoded data to tree.
  104. public TreeNode deserialize(String data) {
  105. Deque<String> nodes = new LinkedList<>();
  106. nodes.addAll(Arrays.asList(data.split(spliter)));
  107. return buildTree(nodes);
  108. }
  109. private TreeNode buildTree(Deque<String> nodes) {
  110. String val = nodes.remove();
  111. if (val.equals(NN)) return null;
  112. else {
  113. TreeNode node = new TreeNode(Integer.valueOf(val));
  114. node.left = buildTree(nodes);
  115. node.right = buildTree(nodes);
  116. return node;
  117. }
  118. }
  119. }
  120. //方法三:别人写的,BFS
  121. public static class Codec3 {
  122. public String serialize(TreeNode root) {
  123. if (root == null) return "";
  124. Queue<TreeNode> q = new LinkedList<>();
  125. StringBuilder res = new StringBuilder();
  126. q.add(root);
  127. while (!q.isEmpty()) {
  128. TreeNode node = q.poll();
  129. if (node == null) {
  130. res.append("n ");
  131. continue;
  132. }
  133. res.append(node.val + " ");
  134. q.add(node.left);
  135. q.add(node.right);
  136. }
  137. return res.toString();
  138. }
  139. public TreeNode deserialize(String data) {
  140. if (data == "") return null;
  141. Queue<TreeNode> q = new LinkedList<>();
  142. String[] values = data.split(" ");
  143. TreeNode root = new TreeNode(Integer.parseInt(values[0]));
  144. q.add(root);
  145. for (int i = 1; i < values.length; i++) {
  146. TreeNode parent = q.poll();
  147. if (!values[i].equals("n")) {
  148. TreeNode left = new TreeNode(Integer.parseInt(values[i]));
  149. parent.left = left;
  150. q.add(left);
  151. }
  152. if (!values[++i].equals("n")) {
  153. TreeNode right = new TreeNode(Integer.parseInt(values[i]));
  154. parent.right = right;
  155. q.add(right);
  156. }
  157. }
  158. return root;
  159. }
  160. }
  161. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. import com.lun.hard.SerializeAndDeserializeBinaryTree.Codec;
  4. import com.lun.hard.SerializeAndDeserializeBinaryTree.Codec2;
  5. import com.lun.hard.SerializeAndDeserializeBinaryTree.Codec3;
  6. import com.lun.util.BinaryTree;
  7. import com.lun.util.BinaryTree.TreeNode;
  8. public class SerializeAndDeserializeBinaryTreeTest {
  9. @Test
  10. public void test() {
  11. Codec ser = new Codec();
  12. Codec deser = new Codec();
  13. TreeNode node1 = BinaryTree.integers2BinaryTree(1,2,3,null,null,4,5);
  14. String str1 = ser.serialize(node1);
  15. assertEquals("1,2,3,N,N,4,5", str1);
  16. assertTrue(BinaryTree.equals(node1, deser.deserialize(str1)));
  17. String str2 = ser.serialize(null);
  18. assertEquals("", str2);
  19. assertNull(deser.deserialize(str2));
  20. TreeNode node3 = BinaryTree.integers2BinaryTree(1);
  21. String str3 = ser.serialize(node3);
  22. assertEquals("1", str3);
  23. assertTrue(BinaryTree.equals(node3, deser.deserialize(str3)));
  24. TreeNode node4 = BinaryTree.integers2BinaryTree(1,2);
  25. String str4 = ser.serialize(node4);
  26. assertEquals("1,2,N", str4);
  27. assertTrue(BinaryTree.equals(node4, deser.deserialize(str4)));
  28. TreeNode node5 = BinaryTree.integers2BinaryTree(4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2);
  29. String str5 = ser.serialize(node5);
  30. assertTrue(BinaryTree.equals(node5, deser.deserialize(str5)));
  31. TreeNode node6 = BinaryTree.integers2BinaryTree(-1,0,1);
  32. String str6 = ser.serialize(node6);
  33. assertTrue(BinaryTree.equals(node6, deser.deserialize(str6)));
  34. }
  35. @Test
  36. public void test2() {
  37. Codec2 ser = new Codec2();
  38. Codec2 deser = new Codec2();
  39. TreeNode node1 = BinaryTree.integers2BinaryTree(1,2,3,null,null,4,5);
  40. String str1 = ser.serialize(node1);
  41. assertTrue(BinaryTree.equals(node1, deser.deserialize(str1)));
  42. String str2 = ser.serialize(null);
  43. assertNull(deser.deserialize(str2));
  44. TreeNode node3 = BinaryTree.integers2BinaryTree(1);
  45. String str3 = ser.serialize(node3);
  46. assertTrue(BinaryTree.equals(node3, deser.deserialize(str3)));
  47. TreeNode node4 = BinaryTree.integers2BinaryTree(1,2);
  48. String str4 = ser.serialize(node4);
  49. assertTrue(BinaryTree.equals(node4, deser.deserialize(str4)));
  50. TreeNode node5 = BinaryTree.integers2BinaryTree(4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2);
  51. String str5 = ser.serialize(node5);
  52. assertTrue(BinaryTree.equals(node5, deser.deserialize(str5)));
  53. TreeNode node6 = BinaryTree.integers2BinaryTree(-1,0,1);
  54. String str6 = ser.serialize(node6);
  55. assertTrue(BinaryTree.equals(node6, deser.deserialize(str6)));
  56. }
  57. @Test
  58. public void test3() {
  59. Codec3 ser = new Codec3();
  60. Codec3 deser = new Codec3();
  61. TreeNode node1 = BinaryTree.integers2BinaryTree(1,2,3,null,null,4,5);
  62. String str1 = ser.serialize(node1);
  63. assertTrue(BinaryTree.equals(node1, deser.deserialize(str1)));
  64. String str2 = ser.serialize(null);
  65. assertNull(deser.deserialize(str2));
  66. TreeNode node3 = BinaryTree.integers2BinaryTree(1);
  67. String str3 = ser.serialize(node3);
  68. assertTrue(BinaryTree.equals(node3, deser.deserialize(str3)));
  69. TreeNode node4 = BinaryTree.integers2BinaryTree(1,2);
  70. String str4 = ser.serialize(node4);
  71. assertTrue(BinaryTree.equals(node4, deser.deserialize(str4)));
  72. TreeNode node5 = BinaryTree.integers2BinaryTree(4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2);
  73. String str5 = ser.serialize(node5);
  74. assertTrue(BinaryTree.equals(node5, deser.deserialize(str5)));
  75. TreeNode node6 = BinaryTree.integers2BinaryTree(-1,0,1);
  76. String str6 = ser.serialize(node6);
  77. assertTrue(BinaryTree.equals(node6, deser.deserialize(str6)));
  78. }
  79. }

发表评论

表情:
评论列表 (有 0 条评论,71人围观)

还没有评论,来说两句吧...

相关阅读